一、命令模式核心思想
命令模式(Command Pattern)是一种行为型设计模式,其核心在于将请求封装成独立对象,从而使不同的请求、队列或日志请求成为可能,同时支持可撤销的操作。
模式包含四个关键角色:
- 命令接口(Command):声明执行操作的接口
- 具体命令(ConcreteCommand):将接收者绑定到动作
- 调用者(Invoker):接收命令并执行
- 接收者(Receiver):知道如何执行请求的具体操作
二、实战示例:智能家居控制
假设我们有一个智能家居系统,需要控制灯光和空调设备:
// 接收者 - 设备类
class Light {
public void turnOn() { System.out.println("灯光已打开"); }
public void turnOff() { System.out.println("灯光已关闭"); }
}
class AirConditioner {
public void turnOn() { System.out.println("空调已开启"); }
public void setTemperature(int temp) {
System.out.println("空调温度设置为:" + temp + "℃");
}
}
// 命令接口
interface Command {
void execute();
void undo();
}
// 具体命令
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) { this.light = light; }
@Override
public void execute() { light.turnOn(); }
@Override
public void undo() { light.turnOff(); }
}
class TemperatureCommand implements Command {
private AirConditioner ac;
private int prevTemp;
private int newTemp;
public TemperatureCommand(AirConditioner ac, int temp) {
this.ac = ac;
this.newTemp = temp;
}
@Override
public void execute() {
prevTemp = 26; // 假设默认26度
ac.setTemperature(newTemp);
}
@Override
public void undo() {
ac.setTemperature(prevTemp);
}
}
// 调用者 - 遥控器
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
public void pressUndo() {
command.undo();
}
}
// 客户端使用
public class Client {
public static void main(String[] args) {
RemoteControl remote = new RemoteControl();
Light light = new Light();
AirConditioner ac = new AirConditioner();
// 控制灯光
remote.setCommand(new LightOnCommand(light));
remote.pressButton(); // 打开灯光
remote.pressUndo(); // 撤销操作(关闭灯光)
// 控制空调温度
remote.setCommand(new TemperatureCommand(ac, 24));
remote.pressButton(); // 设置温度24度
remote.pressUndo(); // 恢复之前温度
}
}
三、模式优势与应用场景
命令模式的主要优势包括:
- 解耦调用者与接收者:调用者无需知道接收者的具体接口
- 支持撤销/重做操作:通过维护命令历史实现
- 支持事务操作:将多个命令组合成复合命令
- 支持队列请求:命令可以排队执行或延迟执行
典型应用场景:
- 需要回调机制的系统
- 需要实现命令队列的系统
- 需要支持撤销/恢复操作的应用
- 需要记录操作日志的场景
命令模式通过将操作请求封装为对象,为复杂的操作控制提供了高度灵活性,是许多高级功能实现的基石模式。
473

被折叠的 条评论
为什么被折叠?



