命令模式:在请求者和响应者之间,通过传递命令实现解耦。
实例:电视遥控器,餐厅里的订单
public interface Command {
public void execute();
}
public class ConcreteCommand implements Command {
private Receiver receiver = null;
private String state;
public ConcreteCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
}
public class Receiver {
public void action(){
//真正执行命令操作的功能代码
}
}
public class Invoker {
private Command command = null;
public void setCommand(Command command) {
this.command = command;
}
public void runCommand() {
command.execute();
}
}
public class Client {
public void assemble(){
//创建接收者
Receiver receiver = new Receiver();
//创建命令对象,设定它的接收者
Command command = new ConcreteCommand(receiver);
//创建Invoker,把命令对象设置进去
Invoker invoker = new Invoker();
invoker.setCommand(command);
}
}