状态模式
1通过状态来控制行为(方法)
2一个状态一个行为(方法)
3每个状态对应每个状态类,该类负责对应状态的行为
4定义:允许对象在内部状态改变时,同时改变它的行为,对象看起来好像修改了他的类
5允许context随着状态的改变而改变行为,状态转换可以由context或者state来控制
6缺点:使设计类的数目变多
7状态类可以由多个context共享
8:context执行handle方法,本质是执行对应的状态实现类的handle方法
4图(与策略模式一样)
public interface State {
public void handle();
}
public class StopState implements State {
Context context;
public StopState(Context context) {
this.context = context;
context.setState(this);
}
public void handle() {
System.out.println("StopState handle");
}
}
public class StartState implements State {
Context context;
public StartState(Context context) {
this.context = context;
context.setState(this);
}
public void handle() {
System.out.println("StartState handle");
}
}
public class Context {
private State state;
public Context() {
state = null;
}
public void setState(State state) {
this.state = state;
}
public void handle() {
state.handle();
}
}
测试
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState(context);
context.handle();
StopState stopState = new StopState(context);
context.handle();
}
}
结果:
StartState handle
StopState handle