Zachary W. Huang

Home Projects Blog Guides Resume

Strategy

Idea: allow for an algorithm to vary its behavior by parameterizing it on a specific “strategy” (encapsulated as an object).

class Context {
  strategy: Strategy;

  setStrategy(strategy: Strategy) {
    this.strategy = strategy;
  }

  run(input: any) {
    console.log(this.strategy.run(input));
  }
}

abstract class Strategy {
  abstract run(input: any): any;
}

class StrategyA extends Strategy {
  run(s: string) {
    return s;
  }
}

class StrategyB extends Strategy {
  run(s: string) {
    return s.split("").reverse().join("");
  }
}

class StrategyC extends Strategy {
  run(s: string) {
    return s.split("").join(" ");
  }
}

function main() {
  const context = new Context();
  context.setStrategy(new StrategyA());
  context.run("Hello"); // "Hello"
  context.setStrategy(new StrategyB());
  context.run("Hello"); // "olleH"
  context.setStrategy(new StrategyC());
  context.run("Hello"); // "H e l l o"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024