Command Pattern
Posted by Dustin Boston in Design Patterns.
The Command Pattern is a behavioral design pattern that encapsulates requests as objects, enabling parameterization, queuing, and logging of operations for greater flexibility in software design.
The Command Pattern is a behavioral design pattern that encapsulates requests as objects, allowing for greater flexibility in software design. By turning requests into objects, this pattern enables features like parameterization, queuing, and logging of operations. It is particularly useful in scenarios where actions need to be executed, delayed, or undone dynamically.
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();