《PHP編程:PHP實(shí)現(xiàn)的策略模式簡單示例》要點(diǎn):
本文介紹了PHP編程:PHP實(shí)現(xiàn)的策略模式簡單示例,希望對您有用。如果有疑問,可以聯(lián)系我們。
本文實(shí)例講述了PHP實(shí)現(xiàn)的策略模式.分享給大家供大家參考,具體如下:PHP實(shí)戰(zhàn)
比如說購物車系統(tǒng),在給商品計算總價的時候,普通會員肯定是商品單價乘以數(shù)量,但是對中級會員提供8者折扣,對高級會員提供7折折扣,這種場景就可以使用策略模式實(shí)現(xiàn):PHP實(shí)戰(zhà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 ?>
更多關(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í)戰(zhàn)
希望本文所述對大家PHP程序設(shè)計有所幫助.PHP實(shí)戰(zhàn)
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/228.html