本文實例講述了PHP實現(xiàn)的策略模式。分享給大家供大家參考,具體如下:比如說購物車系統(tǒng),在給商品計算總價的時候,普通會員肯定是商品單價乘以數(shù)量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模......
以下是【金聰采編】分享的內(nèi)容全文:
以下是【金聰采編】分享的內(nèi)容全文:
本文實例講述了PHP實現(xiàn)的策略模式。分享給大家供大家參考,具體如下:
比如說購物車系統(tǒng),在給商品計算總價的時候,普通會員肯定是商品單價乘以數(shù)量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模式實現(xiàn):
<?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; }}//環(huán)境角色實現(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?>更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。

侵權(quán)舉報/版權(quán)申訴



