状态模式,就是根据当前的状态执行不同的操作,并可以切换状态,红绿灯是个较为形象的例子。

UML图:

【JAVA设计模式】20.状态模式

状态接口及其实现类:

interface State {
    void handle();
}

class ConcreteState1 implements State {
    @Override
    public void handle() {
        System.out.println("ConcreteState1 is handling");
    }
}

context类(多种实现方式,仅写出其中一种):

class Context {

    private State state1 = new ConcreteState1();
    private State state2 = new ConcreteState2();
    private State currentState;

    public Context() {
        currentState = this.state1;
    }

    public void changeState() {
        if (currentState.getClass() == ConcreteState1.class) {
            this.currentState = state2;
        } else if (currentState.getClass() == ConcreteState2.class){
            this.currentState = state1;
        }
    }

    public void doAction() {
        this.currentState.handle();
    }
}

在客户端中调用context的doAction调用当前状态方法,使用changeState更改当前状态:

Context context = new Context();
context.doAction();
context.changeState();
context.doAction();

 

相关文章:

  • 2021-05-22
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-06-28
  • 2021-09-16
猜你喜欢
  • 2021-11-23
  • 2021-10-20
  • 2021-07-05
  • 2021-04-19
  • 2021-10-21
  • 2021-10-20
  • 2022-01-22
相关资源
相似解决方案