Intent
- Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
- An object-oriented state machine
- Wrapper + polymorphic wrappee + collaboration
Structure
state by keith
- 代码:
public class State {
public static void main(String[] args) {
State state = new State();
state.test();
}
private void test() {
Context context = new Context();
context.request();
context.request();
}
class Context {
BaseState state;
public Context() {
this.state = new StartState(this);
}
public void setState(BaseState state){
this.state=state;
}
public void request() {
state.handle();
}
}
// base state
interface BaseState {
void handle();
}
// change the state internally
class StartState implements BaseState {
Context context;
public StartState(Context context) {
this.context = context;
}
@Override
public void handle() {
System.out.println("start it.");
context.setState(new StopState());
}
}
class StopState implements BaseState {
@Override
public void handle() {
System.out.println("stop it.");
}
}
}
- Output
start it.
stop it.
Notice:
- 状态模式中,状态本身会包含Context的引用,从而实现状态迁移 ,但策略模式则没有Context的引用;
- 策略模式是由客户端进行处理的,而状态的改变Context或者State对象都可以进行。
Refenrence
- Design Patterns
- 设计模式
- 状态模式和策略模式的相似与不同
网友评论