php设计模式之命令模式使用示例_PHP

WBOY
Release: 2016-06-01 11:56:21
Original
828 people have browsed it

命令类:
1.命令角色:声明了一个给所有具体命令类的抽象接口。这是一个抽象角色。
2.具体命令角色:定义一个接受者和行为之间的弱耦合;实现execute方法,负责调用接受的相应操作。execute()方法通常叫做执行方法
3.客户角色:创建一个具体命令对象并确定其接受者。
4.请求者角色:负责调用命令对象执行请求,相关的方法叫做行动方法。
5.接受者角色:负责具体实施和执行一个请求。
作用:
1.抽象出待执行的动作以参数化对象。
2.在不同的时刻指定、排列和执行请求。
3.支持取消操作
4.支持修改日志

复制代码 代码如下:
//命令接口
interface Command{
     public function execute();
}
//具体命令
class ConcreteCommand implements Command{
     private $_receiver;
     public function __construct($receiver){
          $this->_receiver = $receiver;
     }
     public function execute(){
          $this->_receiver->action();
     }
}

//接受者
class Receiver{
     private $_name;
     public function __construct($name){
          $this->_name = $name;
     }
     //行动方法
     public function action(){
          echo $this->_name.'do action .
';
     }
}
//请求者
class Invoker{
     private $_command;
     public function __construct($command){
          $this->_command = $command;
     }
     public function action(){
          $this->_command->execute();
     }
}

//客户端
class  Client{
     public static function main(){
          $receiver = new Receiver('jaky');
          $command = new ConcreteeCommand($receiver);
          $invoker = new Invoker($command);
          $invoker->action();
     }
}
Client::main();
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!