Skip to content

Commit

Permalink
Add command pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
davideme committed Jan 15, 2024
1 parent e328345 commit eb238bd
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions typescript/src/patterns/Behavioral/Command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Higher-order function as Command
type Command = () => void;

// Concrete Commands
const simpleCommand = (payload: string): Command => {
return () => {
console.log(`Simple Command: See, I can do simple things like printing (${payload})`);
};
};

const complexCommand = (receiver: Receiver, a: string, b: string): Command => {
return () => {
console.log('Complex Command: Complex stuff should be done by a receiver object.');
receiver.doSomething(a);
receiver.doSomethingElse(b);
};
};

// Receiver
class Receiver {
doSomething(a: string): void {
console.log(`Receiver: Working on (${a}.)`);
}

doSomethingElse(b: string): void {
console.log(`Receiver: Also working on (${b}.)`);
}
}

// Invoker
class Invoker {
private onStart: Command | undefined;
private onFinish: Command | undefined;

setOnStart(command: Command): void {
this.onStart = command;
}

setOnFinish(command: Command): void {
this.onFinish = command;
}

doSomethingImportant(): void {
console.log('Invoker: Does anybody want something done before I begin?');
this.onStart?.();

console.log('Invoker: ...doing something really important...');

console.log('Invoker: Does anybody want something done after I finish?');
this.onFinish?.();
}
}

// Client code
const invoker = new Invoker();
const receiver = new Receiver();
invoker.setOnStart(simpleCommand('Say Hi!'));
invoker.setOnFinish(complexCommand(receiver, 'Send email', 'Save report'));

invoker.doSomethingImportant();

0 comments on commit eb238bd

Please sign in to comment.