Home  >  Article  >  Web Front-end  >  Learn the state pattern of JavaScript design patterns_javascript skills

Learn the state pattern of JavaScript design patterns_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:20:491169browse

The key to the state model is to distinguish the internal state of things. Changes in the internal state of things often bring about changes in the behavior of things.

When the light is on, if you press the switch, the light will switch to off state; if you press the switch again, the light will turn on again. The same switch behaves differently in different states.

1. Finite state machine

  • The total number of states (state) is limited.
  • At any moment, you are only in one state.
  • Under certain conditions, there will be a transition from one state to another.

Allows an object to change its behavior when its internal state changes, making the object appear to modify its class.
Explanation:
(1) Encapsulate the state into an independent class and delegate the request to the current state object. When the internal state of the object changes, different behavior changes will occur.
(2) The objects used have completely different behaviors (delegation effect) in different states

When it comes to encapsulation, priority is generally given to encapsulating the behavior of the object rather than the state of the object.
But in the state pattern, it's just the opposite. The key to the state pattern is to encapsulate each state of things into a separate class.

2. Example

Lighting program (low light –> strong light –> light off) cycle

// 关灯
var OffLightState = function(light) {
  this.light = light;
};
// 弱光
var OffLightState = function(light) {
  this.light = light;
};
// 强光
var StrongLightState = function(light) {
  this.light = light;
};

var Light = function(){
  /* 开关状态 */
  this.offLight = new OffLightState(this);
  this.weakLight = new WeakLightState(this);
  this.strongLight = new StrongLightState(this);
  /* 快关按钮 */
  this.button = null;
};
Light.prototype.init = function() {
  var button = document.createElement("button"),
    self = this;
  this.button = document.body.appendChild(button);
  this.button.innerHTML = '开关';
  this.currentState = this.offLight;
  this.button.click = function() {
    self.currentState.buttonWasPressed();
  }
};
// 让抽象父类的抽象方法直接抛出一个异常(避免状态子类未实现buttonWasPressed方法)
Light.prototype.buttonWasPressed = function() {
  throw new Error("父类的buttonWasPressed方法必须被重写");
};
Light.prototype.setState = function(newState) {
  this.currentState = newState;
};

/* 关灯 */
OffLightState.prototype = new Light(); // 继承抽象类
OffLightState.prototype.buttonWasPressed = function() {
  console.log("关灯!");
  this.light.setState(this.light.weakLight);
}
/* 弱光 */
WeakLightState.prototype = new Light();
WeakLightState.prototype.buttonWasPressed = function() {
  console.log("弱光!");
  this.light.setState(this.light.strongLight);
};
/* 强光 */
StrongLightState.prototype = new Light();
StrongLightState.prototype.buttonWasPressed = function() {
  console.log("强光!");
  this.light.setState(this.light.offLight);
};

PS: Additional explanation
The OffLightState, WeakLightState, StrongLightState constructors must be advanced.

new A("a");
var A = function(a) {
  console.log(a)
}

new B("b");
function B(b) {
  console.log(b);
}

Function declarations will be hoisted before ordinary variables.

3. Performance optimization points

(1) How to manage the creation and destruction of state objects?
The first is only created when the state object is needed and then destroyed (the state object is relatively large, preferred),
The other is to create all state objects at the beginning and never destroy them (state changes frequently).
(2) Use flyweight mode to share a state object.

4. JavaScript version of state machine

(1) Directly delegate the request to a literal object for execution through the Function.prototype.call method

// 状态机
var FSM = {
  off: {
    buttonWasPressed: function() {
      console.log("关灯");
      this.button.innerHTML = "下一次按我是开灯";   // 这是Light上的属性!!!
      this.currState = FSM.on;            // 这是Light上的属性!!!
    }
  },
  on: {
    buttonWasPressed: function() {
      console.log("开灯");
      this.button.innerHTML = "下一次按我是关灯";
      this.currState = FSM.off;
    }
  },
};

var Light = function() {
  this.currState = FSM.off;  // 设置当前状态
  this.button = null;
};

Light.prototype.init = function() {
  var button = document.createElement("button");
  self = this;

  button.innerHTML = "已关灯";
  this.button = document.body.appendChild(button);
  this.button.onclick = function() {
    // 请求委托给FSM状态机
    self.currState.buttonWasPressed.call(self);
  }

}

var light = new Light();
light.init();

(2)Use delegate function

var delegate = function(client, delegation) {
  return {
    buttonWasPressed: function() {
      return delegation.buttonWasPressed.apply(client, arguments);
    }
  };
};

// 状态机
var FSM = {
  off: {
    buttonWasPressed: function() {
      console.log("关灯");
      this.button.innerHTML = "下一次按我是开灯";
      this.currState = this.onState;
    }
  },
  on: {
    buttonWasPressed: function() {
      console.log("开灯");
      this.button.innerHTML = "下一次按我是关灯";
      this.currState = this.offState;
    }
  },
};

var Light = function() {
  this.offState = delegate(this, FSM.off);
  this.onState = delegate(this, FSM.on);
  this.currState = this.offState; // 设置当前状态
  this.button = null;
};

Light.prototype.init = function() {
  var button = document.createElement("button");
  self = this;

  button.innerHTML = "已关灯";
  this.button = document.body.appendChild(button);
  this.button.onclick = function() {
    // 请求委托给FSM状态机
    self.currState.buttonWasPressed();
  }
}

var light = new Light();
light.init();

I hope this article will be helpful to everyone learning JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn