PHP中的策略模式是什么

发布时间:2021-07-10 09:47:25 作者:chen
来源:亿速云 阅读:134

这篇文章主要讲解了“PHP中的策略模式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“PHP中的策略模式是什么”吧!

策略模式,又称为政策模式,属于行为型的设计模式。

Gof类图及解释

GoF定义:定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。本模式使得算法可独立于使用它的客户而变化 。

GoF类图

PHP中的策略模式是什么

代码实现

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中的策略模式是什么

完整源码: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();

说明

感谢各位的阅读,以上就是“PHP中的策略模式是什么”的内容了,经过本文的学习后,相信大家对PHP中的策略模式是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 怎么实现php策略模式
  2. 怎么在php中应用策略模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:PHP中实现SSO单点登录的方法

下一篇:phpmailer如何实现发送邮件功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》