js 状态模式

// 不同状态显示不同内容
function stateManage(action){
    if(typeof action == 'number'){
        if(action == 1){
            console.log('success');
        }else if(action == 2){
            console.log('error');
        }else if(action == 3){
            console.log('warning');
        }
    }else{
        if(action[0] == 1 && action[1] == 2){
            console.log('success');
            console.log('error');
        }
    }
}


// 优化 将if判断中分支,转化为对象上的状态,根据状态分发对应的效果(通过状态控制行为)
function stateManage(action){
    this.state = [];
    this.action = {
        1: function(){
            
        },
        2: function(){
            
        },
        3: function(){
            
        }
    };
 }
 
 stateManage.prototype.putAction=function(action){
     if(typeof action == 'number'){
         this.state.push(action);
     }else{
         this.state=this.state.concat(action);
     }
 }
 stateManage.prototype.run=function(){
    this.state.forEach((action)=> {
        this.action[action]();
    })
 }
new stateManage();
stateManage.putAction([1,2]);
stateManage.run();

 

你可能感兴趣的:(js,js)