设计模式 - 命令模式(Command Pattern)
介绍
命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以参数化不同的请求、队列或者记录请求。这种模式通过将请求封装成一个命令对象来解耦发送者和接收者,使得发送者和接收者都不直接依赖于对方。
实现
我们以一个简单的家用电器控制系统为例,来展示如何使用命令模式来发送命令给不同的设备。
定义命令接口
首先定义一个命令接口,它声明了执行命令的方法。
interface Command {
void execute();
void undo();
}
创建具体命令类
然后创建具体的命令类,这些类实现了 Command
接口,并关联一个具体的接收者。
class Light {
public void on() {
System.out.println("Light is on.");
}
public void off() {
System.out.println("Light is off.");
}
}
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
@Override
public void undo() {
light.on();
}
}
创建调用者类
创建一个调用者类,它持有命令对象,并提供执行命令的方法。
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
public void undoButton() {
command.undo();
}
}
使用命令模式
接下来,在主程序中使用命令模式来控制灯光。
public class HomeAutomation {
public static void main(String[] args) {
Light light = new Light();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
RemoteControl remote = new RemoteControl();
// 打开灯光
remote.setCommand(lightOn);
remote.pressButton(); // 输出 "Light is on."
// 关闭灯光
remote.setCommand(lightOff);
remote.pressButton(); // 输出 "Light is off."
// 撤销操作
remote.undoButton(); // 输出 "Light is on."
}
}
使用场景
命令模式适用于以下情况:
- 当你需要参数化对象时。
- 当你需要执行请求,但不想指定请求的接收者。
- 当你需要支持撤销操作时。
- 当你需要将请求放入队列、日志或者记录请求历史时。
总结
命令模式通过将请求封装为对象来解耦发送者和接收者,使得发送者和接收者都不直接依赖于对方。这种方式不仅增加了代码的可维护性和可扩展性,还支持撤销操作、事务处理等功能。
以上就是命令模式的一个实现案例,希望这篇文章能帮助你理解命令模式的使用方式及其优势。
评论区