执行器设计模式是一种常见的软件设计模式,用于将请求和操作解耦。该模式包含一个执行器和一组命令对象,每个命令对象封装了一个操作。执行器可以接收命令对象并将其存储在队列中,然后按顺序执行这些命令。
该模式的主要优点包括:
-
降低了系统的耦合性,因为命令对象和执行器是相互独立的。
-
可以轻松地添加、删除或修改命令对象,而无需修改执行器。
-
可以轻松地实现撤销和重做操作。
-
可以轻松地实现异步执行。
执行器设计模式的主要缺点包括:
-
命令对象可能会占用大量内存。
-
如果命令对象需要访问执行器的状态,那么就需要引入上下文对象,这可能会增加复杂性。
下面是一个简单的示例,说明如何使用执行器设计模式。
// Command interface
interface Command {
void execute();
}
// Concrete command objects
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOn();
}
}
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOff();
}
}
// Executor
class Executor {
private Queue<Command> queue = new LinkedList<>();
public void addCommand(Command command) {
queue.add(command);
}
public void runCommands() {
for (Command command : queue) {
command.execute();
}
}
}
// Usage
public class Main {
public static void main(String[] args) {
Light light = new Light();
Executor executor = new Executor();
executor.addCommand(new LightOnCommand(light));
executor.addCommand(new LightOffCommand(light));
executor.runCommands();
}
}
在上面的示例中,我们定义了一个 Command
接口和两个具体的命令对象 LightOnCommand
和 LightOffCommand
。我们还定义了一个执行器 Executor
,它包含一个命令队列,并提供了添加命令和执行命令的方法。在 Main
类中,我们创建了一个 Light
对象和一个 Executor
对象,并向执行器中添加了两个命令对象。最后,我们调用 runCommands
方法,按顺序执行这些命令。
// 以上内容来自于 ChitGPT “执行器设计模式”