设计模式|状态模式

设计模式 [字体···] [宽度···]

在状态模式中,当一个对象的内在状态改变时允许改变其行为, 这个对象看起来像是改变了它的类。

代码

public abstract class State {
    public String stateName;
    public abstract void handle(Context context);
}
public class Context {
    private State state;

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

    public void setState(State state) {

        System.out.println("当前状态为: "+this.state.stateName);
        this.state = state;
        System.out.println("状态变更为: "+this.state.stateName);
        System.out.println("--------------------");
    }

    public void request(){
        state.handle(this);
    }
}
public class ConcreteStateA extends State {
    public ConcreteStateA(){
        stateName = "状态A";
    }

    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateB());
    }
}
public class ConcreteStateB extends State{
    public ConcreteStateB() {
        stateName = "状态B";
    }

    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}
public class Main {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStateA());

        context.request();
        context.request();
        context.request();
    }
}

//输出
当前状态为: 状态A
状态变更为: 状态B
--------------------
当前状态为: 状态B
状态变更为: 状态A
--------------------
当前状态为: 状态A
状态变更为: 状态B
--------------------