策略模式:定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
1.找出代码中可能变化之处,把他们独立出来,不要和那些不变化的代码混在一起
2.针对借口编程,而不是针对实现编程
3.多用组合少用继承
namespace DesignPatternStrategyPattern;
//定义行为借口 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 "; } } class WildDuck extends Duck { public function hunter() { echo "wild duck is hunting "; } } class FlyPeace implements FlyBehavior { public function fly() { echo "fly peace "; } } class FlyRocket implements FlyBehavior { public function fly() { echo "fly like rocket "; } } class BoomQuake implements QuakeBehavior { public function quake() { echo "quake like a boom "; } } $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