设计模式-javascript实现【状态模式】

定义:允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
其主要原理是将状态封装成独立的类,并将请求委托给当前的状态对象,当对象内部状态变化时,
会带来不同的行为变化。

1. 状态模式类实现方式

// 状态类
class OffLightState {
  constructor(light) {
    this.light = light;
  }
  buttonWasPressed (){
    console.log('weak light');
    this.light.setState(this.light.weakLightState);
  }
}

class WeakLightState {
  constructor(light) {
    this.light = light;
  }
  buttonWasPressed (){
    console.log('strong light');
    this.light.setState(this.light.strongLightState);
  }
}

class StrongLightState {
  constructor(light) {
    this.light = light;
  }
  buttonWasPressed (){
    console.log('off light');
    this.light.setState(this.light.offLightState);
  }
}

class Light {
  constructor() {
    this.offLightState = new OffLightState(this);
    this.weakLightState = new WeakLightState(this);
    this.strongLightState = new StrongLightState(this);
    this.currState = null;
  }
  // 初始化状态
  init() {
    this.currState = this.offLightState;
  }
  // 切换当前状态
  setState (newState) {
    this.currState = newState;
  }

  // 将行为委托给当前的状态对象
  buttonWasPressed() {
    this.currState.buttonWasPressed();
  }
}

const light = new Light();
light.init();
light.buttonWasPressed(); // weak light
light.buttonWasPressed(); // strong light
light.buttonWasPressed(); // off light

2. 状态模式对象实现方式

const light = {
  currState: null,
  init: () => {
    this.currState = lightState.off;
  },
  setState: (state) => {
    this.currState = state;
  },
  buttonWasPressed: () => {
    this.currState.buttonWasPressed();
  }
};

// 定义状态对象
const lightState = {
  off: {
    buttonWasPressed: () => {
      console.log('weak light');
      light.setState(lightState.weak);
    }
  },
  weak: {
    buttonWasPressed: () => {
      console.log('strong light');
      light.setState(lightState.strong);
    }
  },
  strong: {
    buttonWasPressed: () => {
      console.log('off light');
      light.setState(lightState.off);
    }
  }
};

light.init();
light.buttonWasPressed();
light.buttonWasPressed();
light.buttonWasPressed();

3. 状态模式的优点

  • 状态模式定义了状态与行为之间的关系,并将它们封装在一个类里。通过增加新的状态类,很容易
    增加新的状态和转换。
  • 避免了Context无限膨胀,状态切换的逻辑被分布在状态类中,也去掉了Context中过多的分支条件
  • 用对象代替字符串来记录当前状态,使得状态的切换更加一目了然。
  • Context中的请求动作和状态类中的封装的行为可以非常容易地独立变化而互不影响。
posted @ 2023-03-07 12:01  箫笛  阅读(53)  评论(0)    收藏  举报