-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |