设计模式(分类) 设计模式(六大原则)
创建型(5种) 工厂方法 抽象工厂模式 单例模式 建造者模式 原型模式
结构型(7种) 适配器模式 装饰器模式 代理模式 外观模式 桥接模式 组合模式 享元模式
行为型(11种) 策略模式 模板方法模式 观察者模式 迭代器模式 责任链模式 命令模式 备忘录模式 状态模式 访问者模式 中介者模式
命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,使得请求的发送者和接收者之间解耦。命令对象可以携带参数,支持撤销操作,并且可以被存储、记录、序列化、排队、日志等,从而为系统提供更大的灵活性。
结构:
原理:
优缺点:
-
优点:
-
缺点:
场景:
代码示例(以Java为例)
// 命令接口
public interface Command {
void execute();
}
// 具体命令类(打开电灯)
public class TurnOnLightCommand implements Command {
private Light light;
public TurnOnLightCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
// 具体命令类(关闭电灯)
public class TurnOffLightCommand implements Command {
private Light light;
public TurnOffLightCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
// 接收者类
public class Light {
public void turnOn() {
System.out.println("Light turned on.");
}
public void turnOff() {
System.out.println("Light turned off.");
}
}
// 调用者类
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 remote = new RemoteControl();
Command turnOnCommand = new TurnOnLightCommand(light);
Command turnOffCommand = new TurnOffLightCommand(light);
remote.setCommand(turnOnCommand);
remote.pressButton(); // 打开电灯
remote.setCommand(turnOffCommand);
remote.pressButton(); // 关闭电灯
}
}
在这个示例中,TurnOnLightCommand
和 TurnOffLightCommand
是具体命令类,它们分别封装了打开和关闭电灯的操作。Light
类是接收者,提供了执行这些操作的方法。RemoteControl
类是调用者,它通过调用命令对象的 execute()
方法来执行请求,而不关心命令的具体实现。