PHP设计模式:策略模式

来源:互联网 发布:mac os 软件推荐 编辑:程序博客网 时间:2024/06/08 01:32

策略模式:它定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

适用场景:
1. 多个类只区别在于表现行为不同,可以使用strategy(策略)模式,在操作时动态选择具体要执行的行为(算法、策略);
2. 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现;
3. 对客户隐藏具体策略(算法)的实现细节,彼此完全独立;

<?php//策略类,定义公共接口abstract class Strategy {    //算法方法    public abstract function doSomething();}//具体的策略类,继承Strategeclass StrategyA extends Strategy {    public function doSomething() {        echo 'Strategy A<br/>';    }}class StrategyB extends Strategy {    public function doSomething() {        echo 'Strategy B<br/>';    }}class StrategyC extends Strategy {    public function doSomething() {        echo 'Strategy C<br>';    }}//ContentStragety 来配置,维护一个对Strategy对象的引用class ContentStrategy {    public $strategy;    public function __construct($strategy) {        $this->strategy = $strategy;    }    public function doStrategy() {        $this->strategy->doSomething();    }}//通过向ContentStrategy传人不同的策略类,实现相同的方法doStrategy()$a = new ContentStrategy(new StrategyA());$b = new ContentStrategy(new StrategyB());$c = new ContentStrategy(new StrategyC());$a->doStrategy();$b->doStrategy();$c->doStrategy();
0 0