命令模式通常包含下面几个角色:
1、Client:创建一个命令,并决定接受者
2、Command:命令接口,定义一个抽象方法
3、ConcreteCommand:具体命令,负责调用接受者的相应操作
4、Invoker:请求者,负责调用命令对象执行请求,调用者可能会对在调用时加入自己需求
5、Receiver:接受者,负责具体实施和执行一次请求
Client
package design.pattern.command; public interface Command { public void execute(); }
Command
package design.pattern.command; public interface Command { public void execute(); }
Receiver
package design.pattern.command; public interface Receiver { public void action(); }
ConcreteConmmand
package design.pattern.command; public class ConcreteCommand implements Command { private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action(); } }
ConcreteReceiver
package design.pattern.command; public class ConcreteReceiver implements Receiver { @Override public void action() { System.out.println("action"); } }