命令模式的定义:
Encapsulated a request as an object ,thereby letting you parameterize clients with different requests, queue or log requests,
and support undoable operations.
将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能
在类图中有三个角色:
Receive接收者角色:该角色就是执行角色,命令传递到这里就会被执行
Command命令角色:需要执行的所有命令都在这里声明
Invoker调用者角色:接收到命令,并执行命令
命令模式是把请求方(Invoker)和执行方(Receiver)分开 //通用Receiver类 public abstract class Receiver{ public abstract void doSomething(); } //具体Receiver类 public class ConcreteReceiver1 extends Receiver{ public void doSomething(){...} } public class ConcreteReciver2 extends Receiver{ public void doSomething(){...} } //抽象Command类 public abstract class Command{ public abstract void execute(); } //具体Command类 public class ConcreteCommand1 extends Command{ private Receiver receiver; public ConcreteCommand1(Receiver receiver){ this.receiver=receiver; } public void execute(){ this.receiver.doSomething(); } } public class ConcreteCommand2 extends Command{ private Receiver receiver; public ConcreteCommand2(Receiver receiver){ this.receiver=receiver; } public void execute(){ this.receiver.doSomething(); } } public class Invoker{ private Command command; public void setCommand(Command _command){ this.command=_command; } public void action(){ this.command.execute(); } } public class Client{ public static void main(String[] args){ Invoker invoker=new Invoker(); Receiver receiver=new ConcreteReceiver1(); Command command=new ConcreteCommand1(receiver); invoker.setCommand(command); invoker.action(); } }