介绍
命令模式是一种数据驱动模式,属于行为型模式,对于请求-执行这一动作做了解耦,请求作为独立的命令包含在对象中传递给调用者,调用者根据命令找到合适的执行命令的对象。
代码示例
现在有购物车增加和移除商品的功能,客户端请求输入产品名称和数量,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();
总结
命令模式解耦了请求和处理的动作,使得请求可以方便的记录日志、撤销或是重做,具有很高的灵活性。
网友评论