如下边wikipedia的例子,State模式中state的子类可以互相切换。我觉得这种设计子类之间需要相互知道,耦合性很高。为什么不考虑让StateContext来维护state子类间切换?
它可以跟据针对state类的调用情况(例如返回值),来切换子类。这样降低了子类之间的耦合性,而且如果增加新的state,修改StateContext就可以了,不用在修改其他跟新state可以切换的旧state.
---------------------------------------------------------------------------
The state interface and two implementations. The state method has a reference to the context object and is able to change its state.
interface State {
public void writeName(StateContext stateContext, String name);
}
class StateA implements State {
public void writeName(StateContext stateContext, String name) {
System.out.println(name.toLowerCase());
stateContext.setState(new StateB());
}
}
class StateB implements State {
private int count=0;
public void writeName(StateContext stateContext, String name){
System.out.println(name.toUpperCase());
// change state after StateB's writeName() gets invoked twice
if(++count>1) {
stateContext.setState(new StateA());
}
}
}
The context class has a state variable which it instantiates in an initial state, in this case StateA. In its method, it uses the corresponding methods of the state object.
public class StateContext {
private State myState;
public StateContext() {
setState(new StateA());
}
// normally only called by classes implementing the State interface
public void setState(State newState) {
this.myState = newState;
}
public void writeName(String name) {
this.myState.writeName(this, name);
}
}
--------------------------------------------------------------------------------------------------
http://en.wikipedia.org/wiki/State_pattern