命令模式:将一个请求封装为一个对象,从而你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销操作。 命令类: 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>?>