十八、行为型(状态模式)
// 状态接口
interface State {
void handle(Context context);
}
// 上下文类
class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle(this);
}
}
// 具体状态类:状态A
class ConcreteStateA implements State {
@Override
public void handle(Context context) {
System.out.println("Handling request in State A");
context.setState(new ConcreteStateB()); // 切换到状态B
}
}
// 具体状态类:状态B
class ConcreteStateB implements State {
@Override
public void handle(Context context) {
System.out.println("Handling request in State B");
context.setState(new ConcreteStateA()); // 切换到状态A
}
}
// 客户端代码
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
// 设置初始状态
context.setState(new ConcreteStateA());
// 发起请求,状态会在内部切换
context.request();
context.request();
context.request();
}
}