PHP實(shí)現(xiàn)的策略模式簡(jiǎn)單示例
本文實(shí)例講述了PHP實(shí)現(xiàn)的策略模式。分享給大家供大家參考,具體如下:
比如說(shuō)購(gòu)物車系統(tǒng),在給商品計(jì)算總價(jià)的時(shí)候,普通會(huì)員肯定是商品單價(jià)乘以數(shù)量,但是對(duì)中級(jí)會(huì)員提供8者折扣,對(duì)高級(jí)會(huì)員提供7折折扣,這種場(chǎng)景就可以使用策略模式實(shí)現(xiàn):
<?php /** * 策略模式實(shí)例 * */ //抽象策略角色《為接口或者抽象類,給具體策略類繼承》 interface Strategy { public function computePrice($price); } //具體策略角色-普通會(huì)員策略類 class GenernalMember implements Strategy { public function computePrice($price) { return $price; } } //具體策略角色-中級(jí)會(huì)員策略類 class MiddleMember implements Strategy { public function computePrice($price) { return $price * 0.8; } } //具體策略角色-高級(jí)會(huì)員策略類 class HignMember implements Strategy { public function computePrice($price) { return $price * 0.7; } } //環(huán)境角色實(shí)現(xiàn)類 class Price { //具體策略對(duì)象 private $strategyInstance; //構(gòu)造函數(shù) public function __construct($instance) { $this->strategyInstance = $instance; } public function compute($price) { return $this->strategyInstance->computePrice($price); } } //客戶端使用 $p = new Price(new HignMember()); $totalPrice = $p->compute(100); echo $totalPrice; //70 ?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語(yǔ)法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
PHP生成驗(yàn)證碼時(shí)“圖像因其本身有錯(cuò)無(wú)法顯示”的解決方法
以下是對(duì)PHP生成驗(yàn)證碼時(shí)“圖像因其本身有錯(cuò)無(wú)法顯示”的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08php使用ffmpeg獲取視頻信息并截圖的實(shí)現(xiàn)方法
這篇文章主要介紹了php使用ffmpeg獲取視頻信息并截圖的實(shí)現(xiàn)方法,實(shí)例分析了php操作視頻與圖像的相關(guān)技巧,需要的朋友可以參考下2016-05-05