>  기사  >  백엔드 개발  >  php设计模式之命令模式_PHP教程

php设计模式之命令模式_PHP教程

WBOY
WBOY원래의
2016-07-20 11:13:39944검색

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

<?<span php
</span><span //</span><span 命令接口</span>
<span interface</span><span  Command{
     </span><span public</span> <span function</span><span  execute();
}
</span><span //</span><span 具体命令</span>
<span class</span> ConcreteCommand <span implements</span><span  Command{
     </span><span private</span> <span $_receiver</span><span ;
     </span><span public</span> <span function</span> __construct(<span $receiver</span><span ){
          </span><span $this</span>->_receiver = <span $receiver</span><span ;
     }
     </span><span public</span> <span function</span><span  execute(){
          </span><span $this</span>->_receiver-><span action();
     }
}
 
</span><span //</span><span 接受者</span>
<span class</span><span  Receiver{
     </span><span private</span> <span $_name</span><span ;
     </span><span public</span> <span function</span> __construct(<span $name</span><span ){
          </span><span $this</span>->_name = <span $name</span><span ;
     }
     </span><span //</span><span 行动方法</span>
     <span public</span> <span function</span><span  action(){
          </span><span echo</span> <span $this</span>->_name.'do action .<br/>'<span ;
     }
}
</span><span //</span><span 请求者</span>
<span class</span><span  Invoker{
     </span><span private</span> <span $_command</span><span ;
     </span><span public</span> <span function</span> __construct(<span $command</span><span ){
          </span><span $this</span>->_command = <span $command</span><span ;
     }
     </span><span public</span> <span function</span><span  action(){
          </span><span $this</span>->_command-><span execute();
     }
}
 
</span><span //</span><span 客户端</span>
<span class</span><span   Client{
     </span><span public</span> <span static</span> <span function</span><span  main(){
          </span><span $receiver</span> = <span new</span> Receiver('jaky'<span );
          </span><span $command</span> = <span new</span> ConcreteeCommand(<span $receiver</span><span );
          </span><span $invoker</span> = <span new</span> Invoker(<span $command</span><span );
          </span><span $invoker</span>-><span action();
     }
}
Client</span>::<span main();
</span>?>

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440346.htmlTechArticle命令模式: 将一个请求封装为一个对象,从而你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销操作。...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.