1. 程式人生 > >PHP策略模式實現

PHP策略模式實現

int 所有 BE lpad interface text 調用 ron php

一、意圖
定義一系列的算法,把它們一個個封裝起來,並且使它們可相互替換。策略模式可以使算法可獨立於使用它的客戶而變化
策略模式變化的是算法
二、策略模式結構圖

技術分享圖片

三、策略模式中主要角色
抽象策略(Strategy)角色:定義所有支持的算法的公共接口。通常是以一個接口或抽象來實現。Context使用這個接口來調用其ConcreteStrategy定義的算法
具體策略(ConcreteStrategy)角色:以Strategy接口實現某具體算法
環境(Context)角色:持有一個Strategy類的引用,用一個ConcreteStrategy對象來配置
四、策略模式的優點和缺點
策略模式的優點:
1、策略模式提供了管理相關的算法族的辦法
2、策略模式提供了可以替換繼承關系的辦法 將算封閉在獨立的Strategy類中使得你可以獨立於其Context改變它
3、使用策略模式可以避免使用多重條件轉移語句。
策略模式的缺點:

1、客戶必須了解所有的策略 這是策略模式一個潛在的缺點
2、Strategy和Context之間的通信開銷
3、策略模式會造成很多的策略類
五、策略模式適用場景
1、許多相關的類僅僅是行為有異。“策略”提供了一種用多個行為中的一個行為來配置一個類的方法
2、需要使用一個算法的不同變體。
3、算法使用客戶不應該知道的數據。可使用策略模式以避免暴露復雜的,與算法相關的數據結構
4、一個類定義了多種行為,並且 這些行為在這個類的操作中以多個形式出現。將相關的條件分支移和它們各自的Strategy類中以代替這些條件語句
六、策略模式與其它模式
Template模式:模板方法模式與策略模式的不同在於,策略模式使用委派的方法提供不同的算法行為,而模板方法使用繼承的方法提供不同的算法行為
享元模式(flyweight模式):
如果有多個客戶端對象需要調用 同樣的一睦策略類的話,就可以使它們實現享元模式
七、策略模式PHP示例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 <?php
/** * 抽象策略角色,以接口實現 */ interface Strategy { /** * 算法接口 */ public function algorithmInterface(); } /** * 具體策略角色A */ class ConcreteStrategyA implements Strategy { public function algorithmInterface() { echo ‘algorithmInterface A<br />‘; } } /** * 具體策略角色B */ class ConcreteStrategyB implements Strategy { public function algorithmInterface() { echo ‘algorithmInterface B<br />‘; } } /** * 具體策略角色C */ class ConcreteStrategyC implements Strategy { public function algorithmInterface() { echo ‘algorithmInterface C<br />‘; } } /** * 環境角色 */ class Context { /* 引用的策略 */ private $_strategy; public function __construct(Strategy $strategy) { $this->_strategy = $strategy; } public function contextInterface() { $this->_strategy->algorithmInterface(); } } /** * 客戶端 */ class Client { /** * Main program. */ public static function main() { $strategyA = new ConcreteStrategyA(); $context = new Context($strategyA); $context->contextInterface(); $strategyB = new ConcreteStrategyB(); $context = new Context($strategyB); $context->contextInterface(); $strategyC = new ConcreteStrategyC(); $context = new Context($strategyC); $context->contextInterface(); } } Client::main(); ?>

PHP策略模式實現