Skip to content

Instantly share code, notes, and snippets.

@jinnyMcKindy
Created January 9, 2022 14:23
Show Gist options
  • Save jinnyMcKindy/e2180848507043a7a88f4ccb708651ca to your computer and use it in GitHub Desktop.
Save jinnyMcKindy/e2180848507043a7a88f4ccb708651ca to your computer and use it in GitHub Desktop.
Strategy
class Context {
private strategy: Strategy;
constructor(strategy: Strategy) {
this.strategy = strategy;
}
public setStrategy(strategy: Strategy) {
this.strategy = strategy;
}
public doSomeBusinessLogic(): void {
const result = this.strategy.printText("test")
}
}
interface Strategy {
printText(data: string): void;
}
class consoleStrategy implements Strategy {
public printText(data: string): void {
console.log(data)
}
}
class alertStrategy implements Strategy {
public printText(data: string): void{
alert(data)
}
}
const context = new Context(new consoleStrategy());
context.doSomeBusinessLogic();
context.setStrategy(new alertStrategy());
context.doSomeBusinessLogic();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment