JavaScript state mode example

1. State mode definition: Allow an object to change its behavior when its internal state changes. The object seems to modify its class.

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

Three, there is a good example as follows, the code is as follows:

var delegate = function(client, delegation){
     return{
         buttonWasPressed: function(){ //将客户的操作委托给delegation对象
              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(){
        self.currState.buttonWasPressed();
    }
};

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

Fourth, the advantages and disadvantages of the state mode:

1. Advantages:

   A. Define the relationship between state and behavior, and encapsulate them in a class. By adding new state classes, it is easy to add new states and transitions.

   B. To avoid infinite expansion of Context, the logic of state switching is distributed in state classes, and the original excessive conditional branches in Context are also removed.

   C. Use objects instead of strings to record the current state, making the state switching more clear.

   D. The request action in the Context and the behavior encapsulated in the state class can be easily changed independently without affecting each other.

2. Disadvantages:

      A. Many state classes are defined in the system, and many objects will be added to the system as a result.

      B. Since the logic is scattered in the state class, although unpopular conditional branch statements are avoided, it also causes the problem of logic fragmentation. We cannot see the logic of the entire state machine in one place.

Guess you like

Origin blog.csdn.net/joyksk/article/details/79881275