美文网首页PHP开发PHP经验分享
编程中的设计模式之命令模式

编程中的设计模式之命令模式

作者: phpworkerman | 来源:发表于2020-10-07 09:49 被阅读0次
介绍

命令模式是一种数据驱动模式,属于行为型模式,对于请求-执行这一动作做了解耦,请求作为独立的命令包含在对象中传递给调用者,调用者根据命令找到合适的执行命令的对象。

代码示例

现在有购物车增加和移除商品的功能,客户端请求输入产品名称和数量,Broker 调用类根据传入的命令顺序加入数组中,并依次执行。

<?php
class ClientRequest
{
    public $product;
    public $qty = 1;

    public function __construct($product = 'T恤', $qty = 1)
    {
        $this->product = $product;
        $this->qty = $qty;
    }

    public function add()
    {
        echo "添加 $this->qty 件 $this->product 到购物车 <br>";
    }

    public function remove()
    {
        echo "从购物车移除 $this->qty 件 $this->product <br>";
    }
}

interface Cart
{
    public function exec();
}

class AddToCart
{
    private $client;

    public function __construct($request)
    {
        $this->client = $request;
    }

    public function exec()
    {
        $this->client->add();
    }
}

class RemoveToCart
{
    private $client;

    public function __construct($request)
    {
        $this->client = $request;
    }

    public function exec()
    {
        $this->client->remove();
    }
}

class Broker
{
    private $requestList = [];

    public function addList($request)
    {
        $this->requestList[] = $request;
    }

    public function execCommand()
    {
        foreach($this->requestList as $item){
            $item->exec();
        }
    }
}

class DemoPattern
{
    public function handle()
    {
        $request = new ClientRequest('白色T恤',2);
        $addCart = new AddToCart($request);
        $removeCart = new RemoveToCart($request);

        $broker = new Broker();
        $broker->addList($addCart);
        $broker->addList($removeCart);

        $broker->execCommand();
    }
}

$demoPattern = new DemoPattern();
$demoPattern->handle();
总结

命令模式解耦了请求和处理的动作,使得请求可以方便的记录日志、撤销或是重做,具有很高的灵活性。

相关文章

网友评论

    本文标题:编程中的设计模式之命令模式

    本文链接:https://www.haomeiwen.com/subject/skzsektx.html