本文實例講述了PHP實現的策略模式。分享給大家供大家參考,具體如下:比如說購物車系統,在給商品計算總價的時候,普通會員肯定是商品單價乘以數量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模......
以下是【金聰采編】分享的內容全文:
以下是【金聰采編】分享的內容全文:
本文實例講述了PHP實現的策略模式。分享給大家供大家參考,具體如下:
比如說購物車系統,在給商品計算總價的時候,普通會員肯定是商品單價乘以數量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模式實現:
<?php/** * 策略模式實例 * *///抽象策略角色《為接口或者抽象類,給具體策略類繼承》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; }}//環境角色實現類class Price{ //具體策略對象 private $strategyInstance; //構造函數 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相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。

侵權舉報/版權申訴



