命令模式:将一个请求封装为一个对象,从而可以用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void execute();}
public class ConcreteCommand extends Command { public ConcreteCommand(Receiver receiver) { super(receiver); } @Override public void execute() { receiver.action(); }}
public class Receiver { public void action() { System.out.println("执行请求!"); }}
public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); }}
public class CommandDemo { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.setCommand(command); invoker.executeCommand(); }}