Zachary W. Huang
Idea: encapsulate a subroutine/request into an object so that clients can be easily parameterized with different actions. Using this pattern can allow objects to have callbacks, execute requests independently (in time) of when they are made, support undo/logging/transactions, etc.
Connection: In functional languages, this pattern would likely be replaced with anonymous functions or closures.
abstract class Command {
abstract execute(): void;
}
class PrintCommand extends Command {
execute() {
console.log("Hello");
}
}
class Client {
command: Command
constructor(command: Command) {
this.command = command;
}
doThing() {
this.command.execute();
this.command.execute();
}
}
function main() {
const client = new Client(new PrintCommand());
client.doThing(); // "Hello Hello"
}