Skip to content

Instantly share code, notes, and snippets.

@bernbecht
Created June 28, 2021 16:29
Show Gist options
  • Save bernbecht/e8cda4fd6c1f95090ca1fe8c304c7b5f to your computer and use it in GitHub Desktop.
Save bernbecht/e8cda4fd6c1f95090ca1fe8c304c7b5f to your computer and use it in GitHub Desktop.
Strategy Design Patter in TS
// Strategy design pattern
interface QuackBehavior {
quack(): void;
}
class Quack implements QuackBehavior {
quack() {
console.log('quack');
}
}
class Squeack implements QuackBehavior {
quack() {
console.log('squeack');
}
}
class Duck {
quackBehavior: QuackBehavior;
constructor(initQuackBehavior: QuackBehavior) {
this.quackBehavior = initQuackBehavior;
}
quack() {
this.quackBehavior.quack();
}
}
const d1 = new Duck(new Quack());
const d2 = new Duck(new Squeack());
d1.quack();
d2.quack();
d1.quackBehavior = new Squeack();
d1.quack();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment