允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。

简单例子 电灯 A——B——C——A

  • 上下文Context

Light类

  1. class Light {
  2. offLightState = new OffLightState(this); // 持有状态对象的引用
  3. weakLIghtState = new WeakLIghtState(this);
  4. strongLightState = new StrongLightState(this);
  5. button = null;
  6. init() {
  7. var button = document.createElement('button');
  8. this.button = document.body.appendChild(button);
  9. this.button.innerHTML = '开关';
  10. this.currState = this.offLightState;
  11. this.button.onClick = () => {
  12. this.currState.buttonWasPressed(); // 委托给状态类
  13. }
  14. }
  15. setState(state) {
  16. this.currState = state;
  17. }
  18. }
  • 状态类

关闭、弱光、强光

  1. interface LightState {
  2. buttonWasPressed: () => void
  3. }
  4. class OffLightState implements LightState {
  5. constructor(private light) {}
  6. buttonWasPressed() {
  7. console.log('弱光'); // 行为
  8. this.light.setState(this.light) ; // 改变内部状态
  9. }
  10. }

复杂例子文件上传

  • 对比本书例子和工作项目

    缺点

    会定义很多状态类