State machine mode

The characteristics of

  • An object has state changes, — and the state changes are ordered and known —
  • Each state change triggers a logic
  • You can’t always use if… Else to control

introduce

  • Status: During code execution, if there are changes in signature characteristics that cause the flow of the program to change. That feature is the state

  • The state pattern encapsulates various states into individual classes and encapsulates state transitions as well. That this state switch is fixed,

  • There will be no unexpected circumstances that will lead to change. The state mode saves the main program from making circular decisions about the current state and the next state. When adding a state, you only need to add a state class and modify the state transition relationship in the state class. No modifications to the main program are required. That is, state transitions to main program transparency. The main program simply performs different operations according to different states, without considering transitions between states

  • State patterns work well in certain environments. For example, state mode can be used when the program responds to different user actions that are triggered multiple times.

demo

More detailed code

  • For details about state machine factory optimization, see/Demo /10_ State Machine Mode/State machine Factory Mode
Function LigthOnState(light) {this.state = "light "; this.light = light; } function LightOffState(light) {this.state = "light "; this.light = light; } function LightStrongState(light) {this.state = "LightStrongState "; this.light = light; } LigthOnState. Prototype. HandleButtonClick = function () {the console. The log (" has strong light!" ); this.light.setState(this.light.strongState); }; LightStrongState. Prototype. HandleButtonClick = function () {the console. The log (" has to turn off the lights "); this.light.setState(this.light.offState); }; LightOffState. Prototype. HandleButtonClick = function () {the console. The log (" has been turn on the light!" ); this.light.setState(this.light.onState); }; function Light() { this.onState = new LigthOnState(this); this.strongState = new LightStrongState(this); this.offState = new LightOffState(this); this.currentState = null; The console. The log (" build light "); } Light.prototype.setState = function (state) { this.currentState = state; }; Light.prototype.connect = function (btn) { const _self = this; this.currentState = this.offState; btn.click = function () { _self.currentState.handleButtonClick(); }; Console. log(' light has been established with BTN and the current light state is ${this.currentState.state} '); }; Function Button() {console.log(" build BTN "); } const light = new Light(); const btn = new Button(); light.connect(btn); btn.click(); Turn on the light / / BTN. Click (); // btn.click(); / / to turn off the lightsCopy the code