设计模式之命令模式讲解

概念:命令模式(Command Pattern)又称行动(Action)模式或交易(Transaction)模式。将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。

  • 抽象命令:定义要执行的操作。
  • 具体命令:持有命令的真正执行者,并调用其具体操作。
  • 命令接收者:真正的命令执行者,定义所有的具体操作。
  • 命令调用者:接收命令,并调用命令的具体行为。

接下来用一个开关灯的例子,帮助大家理解这个结构。

java 复制代码
public interface Command {
    void execute();
}

public class LightOnCommand implements Command {
    private final Light light;
    public LightOnCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.lightOn();
    }
}

public class LightOffCommand implements Command {
    private final Light light;
    public LightOffCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.lightOff();
    }
}

public class Light {
    public void lightOn() {
        System.out.println("开灯");
    }
    public void lightOff() {
        System.out.println("关灯");
    }
}

public class Invoker {
    private final Command command;
    public Invoker(Command command) {
        this.command = command;
    }
    public void invoke() {
        if (command != null) {
            command.execute();
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Light light = new Light();
        Invoker invokerOn = new Invoker(new LightOnCommand(light));
        Invoker invokerOff = new Invoker(new LightOffCommand(light));
        invokerOn.invoke();
        invokerOff.invoke();
    }
}

如果大家需要视频版本的讲解,欢迎大家关注我的B站:

十五、设计模式之命令模式讲解

相关推荐
触底反弹15 分钟前
🤯 面试被问 AI Workflow 和 Agent 有啥区别?3 张图 + 2 段代码讲清楚!
人工智能·设计模式·面试
杨充21 小时前
10.可测试性实战设计
设计模式·开源·代码规范
杨充21 小时前
9.重构十二式的实战
设计模式·开源·代码规范
杨充21 小时前
6.设计原则的全景图
设计模式·开源·全栈
杨充21 小时前
2.面向对象的特性
设计模式
杨充21 小时前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充21 小时前
8.反模式与坏味道
设计模式·开源·代码规范
杨充21 小时前
3.接口vs抽象类比较
设计模式
咖啡八杯1 天前
文法、BNF与AST
java·设计模式·解释器模式·ast·文法