本文實(shí)例講述了PHP實(shí)現(xiàn)的策略模式。分享給大家供大家參考,具體如下:
比如說購物車系統(tǒng),在給商品計(jì)算總價(jià)的時(shí)候,普通會員肯定是商品單價(jià)乘以數(shù)量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模式實(shí)現(xiàn):
<?php/** * 策略模式實(shí)例 * *///抽象策略角色《為接口或者抽象類,給具體策略類繼承》interface Strategy{ public function computePrice($price);}//具體策略角色-普通會員策略類class GenernalMember implements Strategy{ public function computePrice($price) { return $price; }}//具體策略角色-中級會員策略類class MiddleMember implements Strategy{ public function computePrice($price) { return $price * 0.8; }}//具體策略角色-高級會員策略類class HignMember implements Strategy{ public function computePrice($price) { return $price * 0.7; }}//環(huán)境角色實(shí)現(xiàn)類class Price{ //具體策略對象 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?>希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選