Design pattern eleven, state pattern

The state mode State allows to change its behavior when the internal state of an object changes. This object looks like it has changed its class.

The state mode mainly solves the situation when the conditional expression that controls the state transition of an object is too complicated. By transferring the judgment logic of the state to a series of classes representing different states, complex judgments can be logicalized.

//状态抽象类,定义一个接口以及封装与Context 的一个特定状态相关的行为
public abstract class State {
    
    
    public abstract void Handle(Context context);
}

//Context 维护一个ConcreteState的实例,这个实例定义当前状态
public class Context {
    
    
    private State state;

    public Context(State state) {
    
    
        this.state = state;
    }

    //可读写的状态
    public State getState() {
    
    
        return state;
    }

    public void setState(State state) {
    
    
        this.state = state;
    }

    //对请求做处理,设置下一个状态
    public void Request() {
    
    
        state.Handle(this);
    }
}

//State的具体状态子类,每一个子类实现一个状态
public class ConcreteStateA extends State {
    
    

    //设置下一个状态是 B
    @Override
    public void Handle(Context context) {
    
    
        context.setState(new ConcreteStateB());
        System.out.println("当前状态" + context.getState().getClass().getName());
    }


}

public class ConcreteStateB extends State {
    
    

    //设置下一个状态是 A
    @Override
    public void Handle(Context context) {
    
    
        context.setState(new ConcreteStateA());
        System.out.println("当前状态" + context.getState().getClass().getName());
    }


    public static void main(String[] args) {
    
    
        Context context = new Context(new ConcreteStateA());//初始化为状态A
        
        //不断变化状态
        context.Request();
        context.Request();
        context.Request();
        context.Request();
        
    }
}

Output

当前状态day12state.ConcreteStateB
当前状态day12state.ConcreteStateA
当前状态day12state.ConcreteStateB
当前状态day12state.ConcreteStateA

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629415