设计模式-命令模式

24 阅读1分钟

定义

命令模式,是一种行为设计模式,它将请求或简单操作封装成一个对象,允许使用不同的请求,队列请求,记录日志等,同时支持撤销。

UML 类图

typescript 实现

1. 定义命令接口

interface Command {
  execute(): void;
}

2. 创建具体命令

class ConcreteCommand implements Command {
  private receiver Receiver;
  
  constructor(receiver: Receiver) {
    this.receiver = receiver;
  }
  
  public execute(): void {
    console.log("ConcreteCommand: Executing command...");
    this.receiver.operation();
  }
}

3. 创建接收者

class Receiver {
  public operation(): void {
    console.log("Receiver: Performing operation...");
  }
}

4. 创建调用者

class Invoker {
  private command: Command;

  public setCommand(commnad: Command): void {
    this.command = command;
  }
  public executeCommand(): void {
    console.log("Invoker: Asking the command to execute...");
    this.command.execute();
  }
}

5. 使用示例

const receiver = new Receiver();
const command = new ConcreteCommand(receiver);
const invoker = new Invoker();

invoker.setCommand(command);
invoker.executeCommand();

通用实现