状态模式主要包含三种类型的角色:
上下文(Context):封装了状态的实例,负责维护状态实例,并将请求委托给当前的状态对象。
/**
* @description: 环境类
*/
public class MyContext {
private MyState state;
public void setState(MyState state) {
this.state = state;
}
public void handler() {
state.handler();
}
}
抽象状态(State):定义了表示不同状态的接口,并封装了该状态下的行为。所有具体状态都实现这个接口。
/**
* @description: 抽象状态类
*/
public abstract class MyState {
abstract void handler();
}
具体状态(Concrete State):具体实现了抽象状态角色的接口,并封装了该状态下的行为。
/**
* @description: 具体状态A
*/
public class RedLightState extends MyState{
@Override
void handler() {
System.out.println("红灯停");
}
}
/**
* @description: 具体状态B
*/
public class GreenLightState extends MyState{
@Override
void handler() {
System.out.println("绿灯行");
}
}
/**
* @description: 测试状态模式
*/
public class TestStateModel {
public static void main(String[] args) {
MyContext myContext = new MyContext();
RedLightState redLightState = new RedLightState();
GreenLightState greenLightState = new GreenLightState();
myContext.setState(redLightState);
myContext.handler(); //红灯停
myContext.setState(greenLightState);
myContext.handler(); //绿灯行
}
}