JavaScript's 17-state mode of 23 design patterns

Concept and characteristics

Concept:
State mode refers to when the conditional expression that controls the state transition of an object is too complicated, the judgment logic is extracted and placed in a series of state classes.

Features:

  1. Behaviors in different states are separated to meet the single responsibility principle.
  2. Reduce the interdependence between objects and introduce different states into independent objects to make state transitions more clear.
  3. It is easy to expand, and new states and transitions can be easily added by creating new subclasses.

Structure and realization

Structure: The
state model includes environmental roles, abstract states and concrete states.
Environmental role: Define the initialization state, manage the state, and delegate the state-related operations to the current state object for processing.
Abstract state: The act of encapsulating state.
Specific state: realize the behavior corresponding to the abstract state.

Case:
Implement a function to judge the status of students' scores. Scores less than 60 are scored as [fail]; scores greater than 60 and less than 90 are scored as [medium]; scores greater than or equal to 90 are scored as [excellent].

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>React App</title>
</head>
<body>
<script>
    class StoreContext{
    
    
        constructor(){
    
    
            this.state = new LowState(this);
        }
        setState(state){
    
    
            this.state = state;
        }
        getState(){
    
    
            return this.state;
        }
        //分数合计
        add(score){
    
    
            this.state.addScore(this,score);
        }
    }
    class Score{
    
    
        //抽象方法,检查当前状态
        checkState(context){
    
    }
        //分数合计-状态之间的业务逻辑
        addScore(context,score){
    
    
            console.log("当前分数:"+this.score+",当前状态:"+this.stateName);
            console.log("加上"+score+"之后,");
            this.score += score;
            this.checkState(context);
            console.log("分数为:"+this.score+",状态为:"+context.getState().stateName);
        }
    }
    class LowState extends Score{
    
    
        constructor(state){
    
    
            super(state);
            this.stateName = "不及格";
            this.score = state.score||0;
        }
        checkState(context){
    
    
            if(this.score>=90 ){
    
    
                //大于90分时,状态为【优秀】
                context.setState(new HighState(this))
            }else if(this.score>=60){
    
    
                //大于60分时,状态为【中等】
                context.setState(new MiddleState(this))
            }
        }
    }
    class MiddleState extends Score{
    
    
        constructor(state){
    
    
            super(state);
            this.stateName = "中等";
            this.score = state.score;
        }
        checkState(context){
    
    
            if(this.score<60 ){
    
    
                //小于60分时,状态为【不及格】
                context.setState(new LowState(this))
            }else if(this.score>=90){
    
    
                context.setState(new HighState(this))
            }
        }
    }
    class HighState extends Score{
    
    
        constructor(state){
    
    
            super(state);
            this.stateName = "优秀";
            this.score = state.score;
        }
        checkState(context){
    
    
            if(this.score<60 ){
    
    
                context.setState(new LowState(this))
            }else if(this.score<90){
    
    
                context.setState(new MiddleState(this))
            }
        }
    }
    class Customer{
    
    
        static main(){
    
    
            let context = new StoreContext();
            context.add(30);
            context.add(40);
            context.add(-60);
            context.add(100);
        }
    }
    Customer.main();
</script>
</body>
</html>

Application scenario

  1. When an object's behavior depends on its state, and when it is running, it changes its behavior according to the state.
  2. An object contains a huge branch structure, and these branches are determined by the state of the object.

Applications

Nothing.

to sum up

The status of common front-end functions is mostly [Yes/No], and it is usually solved by if else. Therefore, more complicated state patterns may not be used. But even if there are only two states, if the state-related behavior is more complicated, you can use the state mode to extract them. In addition, if there are more states, it is also suitable to use state mode to separate different state behaviors.

[Environment class]:
1. Initialize the state in the constructor (pass in the current environment as a parameter).
1. Provide methods for setting and obtaining status.
2. Provide business methods and call business methods of abstract classes (passing in context and business parameters).

[Abstract state class]:
1. Provide business methods for environment classes to call, and internally call specific state class methods to change the state.

[Specific status category]:
1. Provide a method to change the status, and use the environment category to set the status according to the incoming parameters.

Guess you like

Origin blog.csdn.net/weixin_44135121/article/details/106017569