26
05月
2020
命令模式
模式定义
命令模式(Command)将请求封装成对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。
命令模式的优势
降低系统的耦合度
新的命令可以很容易地加入到系统中
可以比较容易地设计一个组合命令
代码示例
Command\CommandInterface.class.php
<?php namespace Command; interface CommandInterface { public function execute(); }
Command\HelloCommand.class.php
<?php namespace Command; class HelloCommand implements CommandInterface { protected $output; public function __construct(Receiver $console) { $this->output = $console; } public function execute() { $this->output->write("Hello World\n"); } }
Command\Receiver.class.php
<?php namespace Command; class Receiver { public function write($str) { echo $str; } }
Command\Invoker.class.php
<?php namespace Command; class Invoker { protected $command; public function setCommand(CommandInterface $cmd) { $this->command = $cmd; } public function run() { $this->command->execute(); } }
Command\CommandTest.php
<?php spl_autoload_register(function ($className){ $className = str_replace("\\", "/", $className); include $className . ".class.php"; }); use Command\Invoker; use Command\Receiver; use Command\HelloCommand; $invoker = new Invoker(); $receiver = new Receiver(); $invoker->setCommand(new HelloCommand($receiver)); $invoker->run();
测试示例:
php Command/CommandTest.php 输出: Hello World
总结
命令模式就是将一组对象的相似行为,进行了抽象,将调用者与被调用者之间进行解耦,提高了应用的灵活性。命令模式将调用的目标对象的一些异构性给封装起来,通过统一的方式来为调用者提供服务。
代码地址:https://github.com/798256478/design-patterns/tree/master/Command