执行器设计模式

执行器设计模式是一种常见的软件设计模式,用于将请求和操作解耦。该模式包含一个执行器和一组命令对象,每个命令对象封装了一个操作。执行器可以接收命令对象并将其存储在队列中,然后按顺序执行这些命令。

该模式的主要优点包括:

  1. 降低了系统的耦合性,因为命令对象和执行器是相互独立的。

  2. 可以轻松地添加、删除或修改命令对象,而无需修改执行器。

  3. 可以轻松地实现撤销和重做操作。

  4. 可以轻松地实现异步执行。

执行器设计模式的主要缺点包括:

  1. 命令对象可能会占用大量内存。

  2. 如果命令对象需要访问执行器的状态,那么就需要引入上下文对象,这可能会增加复杂性。

下面是一个简单的示例,说明如何使用执行器设计模式。

// Command interface
interface Command {
    void execute();
}

// Concrete command objects
class LightOnCommand implements Command {
    private Light light;
    
    public LightOnCommand(Light light) {
        this.light = light;
    }
    
    public void execute() {
        light.turnOn();
    }
}

class LightOffCommand implements Command {
    private Light light;
    
    public LightOffCommand(Light light) {
        this.light = light;
    }
    
    public void execute() {
        light.turnOff();
    }
}

// Executor
class Executor {
    private Queue<Command> queue = new LinkedList<>();
    
    public void addCommand(Command command) {
        queue.add(command);
    }
    
    public void runCommands() {
        for (Command command : queue) {
            command.execute();
        }
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
        Light light = new Light();
        Executor executor = new Executor();
        executor.addCommand(new LightOnCommand(light));
        executor.addCommand(new LightOffCommand(light));
        executor.runCommands();
    }
}

在上面的示例中,我们定义了一个 Command 接口和两个具体的命令对象 LightOnCommandLightOffCommand。我们还定义了一个执行器 Executor,它包含一个命令队列,并提供了添加命令和执行命令的方法。在 Main 类中,我们创建了一个 Light 对象和一个 Executor 对象,并向执行器中添加了两个命令对象。最后,我们调用 runCommands 方法,按顺序执行这些命令。 

// 以上内容来自于 ChitGPT “执行器设计模式”

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值