Zachary W. Huang

Home Projects Blog Guides Resume

State

Idea: allow an object to change its behavior based on its internal state, even though its class remains the same (but not the subclass, which is key).

abstract class State {
  abstract doThing1();
  abstract doThing2();
}

class StateA extends State {
  doThing1() {
    console.log("A");
  }
  doThing2() {
    console.log("B");
  }
}

class StateB extends State {
  doThing1() {
    console.log("B");
  }
  doThing2() {
    console.log("A");
  }
}

class Thing {
  state: State;
  flag = true;

  constructor() {
    this.state = new StateA();
  }

  doThing1() {
    this.state.doThing1();
  }

  doThing2() {
    this.state.doThing2();
  }

  changeState() {
    this.flag = !this.flag;
    if (this.flag) {
      this.state = new StateA();
    } else {
      this.state = new StateB();
    }
  }
}

function main() {
  const thing = new Thing();
  thing.doThing1(); // "A"
  thing.doThing2(); // "B"
  thing.changeState();
  thing.doThing1(); // "B"
  thing.doThing2(); // "A"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024