Command

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

type Command = {
  execute(): void;
};

class Invoker {
  execute(command: Command): void {
    command.execute();
  }
}

class Receiver {
  action1(): void {
    console.log("action1");
  }

  action2(): void {
    console.log("action2");
  }
}

class ConcreteCommandA implements Command {
  constructor(private readonly receiver: Receiver) {}

  execute(): void {
    this.receiver.action1();
  }
}

class ConcreteCommandB implements Command {
  constructor(private readonly receiver: Receiver) {}

  execute(): void {
    this.receiver.action2();
  }
}

const client = {
  run(action: number): void {
    const receiver = new Receiver();
    const ccmdA = new ConcreteCommandA(receiver);
    const ccmdB = new ConcreteCommandB(receiver);
    const invoker = new Invoker();

    switch (action) {
      case 1: {
        invoker.execute(ccmdA);
        break;
      }

      case 2: {
        invoker.execute(ccmdB);
        break;
      }

      default: {
        console.log("Invalid action");
      } // Handle invalid actions
    }
  },
};

const example = {
  run(): void {
    client.run(1);
    client.run(2);
    client.run(3); // Example of invalid action
  },
};

example.run();