PHP设计模式之策略模式
策略模式,又称为政策模式,属于行为型的设计模式。
GoF定义:定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。本模式使得算法可独立于使用它的客户而变化 。
GoF类图
代码实现
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
依然还是短信功能,具体的需求可以参看简单工厂模式中的讲解,但是这回我们使用策略模式来实现!
短信发送类图
完整源码:https://github.com/zhangyue0503/designpatterns-php/blob/master/10.strategy/source/strategy-message.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();
说明
策略模式算是一个中场休息,后面还有一大半的模式还没有讲呢,接下来登场的这位可是近几年的网红选手:责任链模式。不要告诉我你没听过这位的大名,Laravel的中间件就是这货的典型的实现哦!!