Learning the state pattern _javascript techniques of JavaScript design patterns

Source: Internet
Author: User
Tags fsm

The key of state mode is to distinguish the internal state of things, and the change of the internal state of things often brings about the behavior change of things.

When the light is on, when the switch is pressed, the light will switch to the closed state, and then press the switch again and the light will be opened again. The same switch in different states, the performance of the behavior is not the same.

One, finite state machine

    • The total number of States (state) is limited.
    • At any moment, only in a state.
    • Under certain conditions, from one state Transition (transition) to another state.

Allows an object to change its behavior when its internal state changes, and the object appears to modify its class.
Explain:
(1) Encapsulate the state into a separate class and delegate the request to the current state object, which brings about different behavioral changes when the internal state of the object changes.
(2) Use of objects, in different states with distinct behavior (delegate effect)

When it comes to encapsulation, it is generally preferable to encapsulate the object's behavior rather than the object's state.
But in the state mode, the key to the state pattern is to encapsulate each state of the thing into a separate class.

Second, the example

Lighting Program (weak light –> strong light –> off light) cycle

Turn off the lamp var offlightstate = function (light) {this.light = light;};
Weak light var offlightstate = function (light) {this.light = light;};

Strong light var stronglightstate = function (light) {this.light = light;};
  var Light = function () {/* switch state/* this.offlight = new Offlightstate (this);
  This.weaklight = new Weaklightstate (this);
  This.stronglight = new Stronglightstate (this);
/* Fast off button/This.button = null;
};
  Light.prototype.init = function () {var button = document.createelement ("button"), self = this;
  This.button = document.body.appendChild (button);
  This.button.innerHTML = ' switch ';
  This.currentstate = This.offlight;
  This.button.click = function () {self.currentState.buttonWasPressed ();
}
}; Let an abstract method of an abstract parent class throw an exception directly (avoid the Buttonwaspressed method not implemented by the state subclass) Light.prototype.buttonWasPressed = function () {throw new Error ("
The Buttonwaspressed method of the parent class must be overridden ");
};

Light.prototype.setState = function (newstate) {this.currentstate = newstate;}; * * Turn off the light/Offlightstate.prototype =New Light (); Inherit abstract class OffLightState.prototype.buttonWasPressed = function () {Console.log ("Turn off the Lights!")
  ");
This.light.setState (This.light.weakLight);
/* Weak light */Weaklightstate.prototype = new Light (); WeakLightState.prototype.buttonWasPressed = function () {Console.log (weak light!)
  ");
This.light.setState (This.light.strongLight);
};
/* Strong Light * * Stronglightstate.prototype = new Light (); StrongLightState.prototype.buttonWasPressed = function () {Console.log (strong light!)
  ");
This.light.setState (This.light.offLight);

 };

PS: Note added
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);
}

The function declaration is elevated before the normal variable.

Third, the performance optimization point

(1) How to manage the creation and destruction of State objects?
The first is created and then destroyed only when the state object is needed (the state object is larger and preferred),
The other is to create all the state objects from the start and never destroy them (the state changes frequently).
(2) Sharing a state object using the meta mode.

Four, JavaScript version of the state machine

(1) Directly delegate the request to a literal object by Function.prototype.call method to execute

State machine
var FSM = {
  off: {
    buttonwaspressed:function () {
      console.log ("Turn off Lights");
      This.button.innerHTML = "Next time I turn on the light";   This is the property on the light!!!
      this.currstate = Fsm.on;            This is the property on the light!!!
    }
  , on
  : {
    buttonwaspressed:function () {
      console.log ("Lights on");
      This.button.innerHTML = "Next time I turn off the light";
      This.currstate = Fsm.off;
    }
  ,
};

var Light = function () {
  this.currstate = Fsm.off;  Sets the current state
  This.button = null;

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

  button.innerhtml = "lights off";
  This.button = document.body.appendChild (button);
  This.button.onclick = function () {
    //request delegated to FSM state machine
    self.currState.buttonWasPressed.call (self);
  }

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

(2) using the delegate function

var delegate = function (client, delegation) {return {buttonwaspressed:function ()} {return Delegation.butto
    Nwaspressed.apply (client, arguments);
}
  };

};
      State machine var FSM = {off: {buttonwaspressed:function () {Console.log ("Turn off Lights");
      This.button.innerHTML = "Next time I turn on the light";
    This.currstate = this.onstate;
      }, on: {buttonwaspressed:function () {Console.log ("lights on");
      This.button.innerHTML = "Next time I turn off the light";
    This.currstate = this.offstate;

}
  },
};
  var Light = function () {this.offstate = delegate (this, fsm.off);
  This.onstate = Delegate (this, fsm.on); This.currstate = this.offstate;
Sets the current state This.button = null;

};
  Light.prototype.init = function () {var button = document.createelement ("button");

  self = this;
  button.innerhtml = "Lights off";
  This.button = document.body.appendChild (button);
  This.button.onclick = function () {//request delegated to FSM state machine self.currState.buttonWasPressed (); } var light = new Light ();
 Light.init ();

Hopefully this article will help you learn about JavaScript programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.