【JAVA设计模式】20.状态模式
状态模式,就是根据当前的状态执行不同的操作,并可以切换状态,红绿灯是个较为形象的例子。
UML图:
状态接口及其实现类:
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();