码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式

时间:2016-06-01 06:46:20      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

策略模式:定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户

1.找出代码中可能变化之处,把他们独立出来,不要和那些不变化的代码混在一起

2.针对借口编程,而不是针对实现编程

3.多用组合少用继承

namespace DesignPattern\StrategyPattern;

//定义行为借口
Interface FlyBehavior { public function fly(); } Interface QuakeBehavior { public function Quake(); }
//定义鸭子抽象类
abstract class Duck { protected $fly; protected $quake; public function __construct(FlyBehavior $fly, QuakeBehavior $quake) { $this -> fly = $fly; $this -> quake = $quake; } public function fly() { $this -> fly -> fly(); } public function quake() { $this -> quake -> quake(); } public function setFlyBehavior(FlyBehavior $fly) { $this -> fly = $fly; } public function setQuakeBehavior(QuakeBehavior $quake) { $this -> quake = $quake; } }

具体实现的分离

class HomeDock extends Duck
    {
        public function cooked()
        {
            echo "home duck be cooked\n";
        }
    }

    class WildDuck extends Duck
    {
        public function hunter()
        {
            echo "wild duck is hunting\n";
        }
    }

    class FlyPeace implements FlyBehavior
    {
        public function fly()
        {
            echo "fly peace\n";
        }
    }

    class FlyRocket implements FlyBehavior
    {
        public function fly()
        {
            echo "fly like rocket\n";
        }
    }

    class BoomQuake implements QuakeBehavior
    {
        public function quake()
        {
            echo "quake like a boom\n";
        }
    }

    $homedock = new HomeDock(new FlyRocket, new BoomQuake);
    $homedock -> cooked();
    $homedock -> quake();
    $homedock -> fly();
    $homedock -> setFlyBehavior(new FlyPeace);
    $homedock -> fly();

输出

home duck be cooked
quake like a boom
fly like rocket
fly peace

 

策略模式

标签:

原文地址:http://www.cnblogs.com/yangxunwu1992/p/5548249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!