State Pattern: allows an object to alter its behavior when its internal state changes. The object will appear to changes its class.
Encapsulate state into separate classes. With the State Pattern, we have a set of behaviors encapsulated int state objects; at any time the context is delegating to one of those states. State Pattern allows a Context to change its behavior as the state of the Context changes.
状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。
定义State接口:
public interface State {
public void responseAction1();
public void responseAction2();
}
定义具体State:
public class StateA implements State {
Context context;
public StateA(Context context) {
this.context = context;
}
@Override
public void responseAction1() {
context.currentState = context.stateB;
// do something
}
@Override
public void responseAction2() {
// TODO Auto-generated method stub
}
}
public class StateB implements State {
Context context;
public StateB(Context context) {
this.context = context;
}
@Override
public void responseAction1() {
// TODO Auto-generated method stub
}
@Override
public void responseAction2() {
// TODO Auto-generated method stub
}
}
定义Context:
public class Context {
State stateA;
State stateB;
State currentState = stateA;
public Context() {
stateA = new StateA(this);
stateB = new StateB(this);
}
public void responseAction1() {
currentState.responseAction1();
}
public void responseAction2() {
currentState.responseAction2();
}
}