2024.11.24命令模式
命令模式(Command Pattern)是一种行为型设计模式,它将请求或简单操作封装为一个对象。这种模式提供了一种方法来参数化其他对象,将操作延迟到适当的时候执行,并支持撤销操作。命令模式通常用于以下场景:
- 需要将操作封装为对象:当需要将操作作为参数传递给其他对象时。
- 需要支持撤销和重做:当需要记录操作历史以支持撤销和重做功能时。
- 需要解耦请求的发送者和接收者:当需要降低系统组件之间的耦合度时。
命令模式的主要组件包括:
- Command(命令接口):定义命令的接口,声明执行操作的方法。
- ConcreteCommand(具体命令):实现Command接口,定义接收者和要执行的操作。
- Client(客户):创建具体的命令对象,并设置其接收者。
- Invoker(调用者):要求命令对象执行请求。
- Receiver(接收者):知道如何实施与执行一个请求相关的操作。
下面是一个简单的命令模式的代码示例:
// 命令接口
public interface Command {
void execute();
}
// 具体命令
public class Light {
public void turnOn() {
System.out.println("Light is on");
}
public void turnOff() {
System.out.println("Light is off");
}
}
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOn();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOff();
}
}
// 调用者
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Light light = new Light();
RemoteControl control = new RemoteControl();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
control.setCommand(lightOn);
control.pressButton(); // Light is on
control.setCommand(lightOff);
control.pressButton(); // Light is off
}
}
在这个例子中,Command
是命令接口,LightOnCommand
和 LightOffCommand
是具体命令,它们分别封装了打开和关闭灯的操作。Light
是接收者,它知道如何实施操作。RemoteControl
是调用者,它通过设置不同的命令来执行不同的操作。Client
是客户端代码,它创建具体的命令对象,并设置调用者。
命令模式的主要优点是它将发起操作的对象(调用者)和执行操作的对象(接收者)解耦,并且可以灵活地新增命令对象,使得系统更加灵活和可扩展。