JS state mode

JS state mode

1 Introduction

State mode (State) allows an object to change its behavior when its internal state changes. The object seems to modify its class. In fact, an object or array is used to record a set of states, each state corresponds to an implementation, and the implementation is executed one by one according to the state.

2. Realization

For example, Super Mario may have several states at the same time, such as jumping, moving, shooting, squatting, etc. If you judge these actions one by one, you need multiple if-elseor switchnot only ugly, but also when there are combined actions. , The implementation will become more complicated, here you can use the state mode to achieve.

The idea of ​​the state mode is: first create a state object or array, save the state variables internally, then encapsulate the state corresponding to each action, and then the state object returns an interface object, which can modify or call the internal state.

const SuperMarry = (function() {    
  let _currentState = [],//state array
      states = {
        jump() {console.log('jump!')},
        move() {console.log('Mobile!')},
        shoot() {console.log('shoot!')},
        squat() {console.log('Squat down!')}
      }
  
  const Action = {
    changeState(arr) {//change the current action
      _currentState = arr
      return this
    },
    goes() {
      console.log('Trigger action')
      _currentState.forEach(T => states[T] && states[T]())
      return this
    }
  }
  
  return {
    change: Action.changeState,
    go: Action.goes
  }
})()

SuperMarry
    .change(['jump','shoot'])
    .go()//Trigger action jump! Shoot!
    .go()//Trigger action jump! Shoot!
    .change(['squat'])
    .go()//Trigger the action to squat down!

Here are ES6some classoptimizations that can be used :

class SuperMarry {
  constructor() {
    this._currentState = []
    this.states = {
      jump() {console.log('jump!')},
      move() {console.log('Mobile!')},
      shoot() {console.log('shoot!')},
      squat() {console.log('Squat down!')}
    }
  }
  
  change(arr) {//change the current action
    this._currentState = arr
    return this
  }
  
  go() {
    console.log('Trigger action')
    this._currentState.forEach(T => this.states[T] && this.states[T]())
    return this
  }
}

new SuperMarry()
    .change(['jump','shoot'])
    .go()//Trigger action jump! Shoot!
    .go()//Trigger action jump! Shoot!
    .change(['squat'])
    .go()//Trigger the action to squat down!

3. Summary

The usage scenarios of the state mode are also particularly clear, with the following two points:

  1. The behavior of an object depends on its state, and it must change its behavior according to the state at runtime.
  2. An operation contains a large number of branch statements, and these branch statements depend on the state of the object. State is usually a representation of one or more enumerated constants.

In short, when you encounter many peers if-elseor switch, you can use the state mode to simplify.

This article is a series of articles, you can refer to each other to confirm and make progress together~

  1. JS abstract factory pattern
  2. JS factory pattern
  3. JS builder mode
  4. JS prototype mode
  5. JS singleton mode
  6. JS callback mode
  7. JS appearance mode
  8. JS adapter mode
  9. JS uses higher-order functions to implement function caching (memo mode)
  10. JS state mode
  11. JS bridge mode
  12. JS observer mode

Most of the posts on the Internet are of different depths, and even some are inconsistent. The articles below are summaries of the learning process. If you find errors, please leave a message to point out~

Reference: "Javascript Design Patterns"-The State Pattern of Zhang Rongming's Design Patterns

Reference: https://cloud.tencent.com/developer/article/1356693 JS State Mode-Cloud + Community-Tencent Cloud