状态模式

2018-08-19  本文已影响0人  hankchang

状态模式

示例


UML

UML.png
// 状态 (红灯, 绿灯, 黄灯)
class State {
  constructor(color) {
    this.color = color;
  }
  handle(context) {
    console.log(`turn to ${this.color} light`);
    context.setState(this);
  }
}

// 主体
class Contest {
  constructor() {
    this.state = null;
  }
  // 获取状态
  getState() {
    return this.state;
  }
  setState(state) {
    this.state = state;
  }
}

// test
const context = new Contest();

const green = new State("green");
const yellow = new State("yellow");
const red = new State("red");

// 绿灯
green.handle(context);
console.log(context.getState());
// 黄灯
yellow.handle(context);
console.log(context.getState());
// 红灯
red.handle(context);
console.log(context.getState());

场景

有限状态机

有限状态机- "收藏" 和 "取消"

有限状态机.png 有限状态机2.png

写一个简单的 Promise

MyPromise.png Promise.png

设计原则验证

上一篇 下一篇

猜你喜欢

热点阅读