命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。[DP]
// 命令接口
interface Command {
void execute();
}
// 具体命令类,实现了命令接口
class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
}
// 接收者类,知道如何执行请求
class Receiver {
public void action() {
System.out.println("Receiver: 执行操作");
}
}
// 调用者类,负责发送命令
class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand() {
command.execute();
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建接收者
Receiver receiver = new Receiver();
// 创建具体命令对象,并将接收者传递给它
Command command = new ConcreteCommand(receiver);
// 创建调用者,并将命令传递给它
Invoker invoker = new Invoker(command);
// 通过调用者执行命令
invoker.executeCommand();
}
}