策略模式,又称为政策模式,属于行为型的设计模式。php
GoF定义:定义一系列的算法,把它们一个个封装起来,而且使它们能够相互替换。本模式使得算法可独立于使用它的客户而变化 。laravel
GoF类图git
代码实现github
interface Strategy{ function AlgorithmInterface(); } class ConcreteStrategyA implements Strategy{ function AlgorithmInterface(){ echo "算法A"; } } class ConcreteStrategyB implements Strategy{ function AlgorithmInterface(){ echo "算法B"; } } class ConcreteStrategyC implements Strategy{ function AlgorithmInterface(){ echo "算法C"; } }
定义算法抽象及实现。算法
class Context{ private $strategy; function __construct(Strategy $s){ $this->strategy = $s; } function ContextInterface(){ $this->strategy->AlgorithmInterface(); } }
定义执行环境上下文。设计模式
$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),想找某工厂(ConcreteStrategy)来作一批手机,经过渠道商(Context)向这个工厂下单制造手机,渠道商直接去联系代工厂(Strategy),而且直接将生产完成的手机发货给我(ContextInterface())。一样的,我不用关心他们的具体实现,我只要监督那个和咱们联系的渠道商就能够啦,是否是很省心!函数
完整代码:https://github.com/zhangyue0503/designpatterns-php/blob/master/10.strategy/source/strategy.php单元测试
依然仍是短信功能,具体的需求能够参看简单工厂模式中的讲解,可是这回咱们使用策略模式来实现!学习
短信发送类图
<?php interface Message { public function send(); } class BaiduYunMessage implements Message { function send() { echo '百度云发送信息!'; } } class AliYunMessage implements Message { public function send() { echo '阿里云发送信息!'; } } class JiguangMessage implements Message { public function send() { echo '极光发送信息!'; } } class MessageContext { private $message; public function __construct(Message $msg) { $this->message = $msg; } public function SendMessage() { $this->message->send(); } } $bdMsg = new BaiduYunMessage(); $msgCtx = new MessageContext($bdMsg); $msgCtx->SendMessage(); $alMsg = new AliYunMessage(); $msgCtx = new MessageContext($alMsg); $msgCtx->SendMessage(); $jgMsg = new JiguangMessage(); $msgCtx = new MessageContext($jgMsg); $msgCtx->SendMessage();
说明
关注公众号:【硬核项目经理】获取最新文章
添加微信/QQ好友:【xiaoyuezigonggong/149844827】免费得PHP、项目管理学习资料
知乎、公众号、抖音、头条搜索【硬核项目经理】
B站ID:482780532