策略模式
Posted 日拱一卒,功不唐捐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了策略模式相关的知识,希望对你有一定的参考价值。
策略模式:定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
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
以上是关于策略模式的主要内容,如果未能解决你的问题,请参考以下文章