在状态模式结构图中,通常包含以下几个角色:
- Context(环境类):也称为上下文类,它是拥有多种状态的对象。在环境类中维护一个抽象状态类State的实例,这个实例定义当前状态。
- State(抽象状态类):用于定义一个接口以封装与环境类的一个特定状态相关的行为。在抽象状态类中声明了各种不同状态对应的方法,并在子类中实现这些方法。
- ConcreteState(具体状态类):它是抽象状态类的子类,每一个子类实现一个与环境类的一个状态相关的行为。
IState
public interface IState {
void handle();
}
ConcreteStateA
public class ConcreteStateB implements IState{
public void handle() {
System.out.println("状态B的动作");
}
}
ConcreteStateB
public class ConcreteStateB implements IState{
public void handle() {
System.out.println("状态B的动作");
}
}
Context
public class Context {
public static final IState STATE_A = new ConcreteStateA();
public static final IState STATE_B = new ConcreteStateB();
private IState currentState = STATE_A;
public void setState(IState state){
this.currentState = state;
}
public void handle(){
this.currentState.handle();
}
}
客户端执行类
public class ClientTest {
public static void main(String[] args) {
Context context = new Context();
context.handle();
context.setState(Context.STATE_B);
context.handle();
}
}
执行结果输出为:
状态A的动作
状态B的动作
举个生活中常见的例子
交通信号灯有三种颜色,红、黄、绿。
它们会按照顺序切换。
我们使用状态模式,通过代码模拟一下三种信号灯的切换。ITrafficState
抽象状态类TrafficStateRed
红灯TrafficStateYellow
黄灯TrafficStateGreen
绿灯TrafficContext
上下文类
public interface ITrafficState {
String getName();
void lightChange(TrafficContext context);
}
@Data
public class TrafficStateRed implements ITrafficState{
private String name = "红灯";
public void lightChange(TrafficContext context) {
context.setCurrentState(TrafficContext.GREEN_LIGHT);
}
}
@Data
public class TrafficStateYellow implements ITrafficState{
private String name = "黄灯";
public void lightChange(TrafficContext context) {
context.setCurrentState(TrafficContext.RED_LIGHT);
}
}
@Data
public class TrafficStateGreen implements ITrafficState{
private String name ="绿灯";
public void lightChange(TrafficContext context) {
context.setCurrentState(TrafficContext.YELLOW_LIGHT);
}
}
public class TrafficContext {
public static final ITrafficState RED_LIGHT = new TrafficStateRed();
public static final ITrafficState GREEN_LIGHT = new TrafficStateGreen();
public static final ITrafficState YELLOW_LIGHT = new TrafficStateYellow();
private ITrafficState currentState = GREEN_LIGHT;
public void setCurrentState(ITrafficState currentState) {
this.currentState = currentState;
}
public void changeLight(){
System.out.print("当前是:" + this.currentState.getName());
this.currentState.lightChange(this);
System.out.println(" || lightChange || 变为 "+this.currentState.getName());
}
}
//客户端测试类
public class ClientTest {
public static void main(String[] args) {
TrafficContext context = new TrafficContext();
//默认绿灯,变为黄灯
context.changeLight();
//黄灯 -> 红灯
context.changeLight();
//红灯 -> 绿灯
context.changeLight();
}
}
执行结果为:
当前是:绿灯 || lightChange || 变为 黄灯
当前是:黄灯 || lightChange || 变为 红灯
当前是:红灯 || lightChange || 变为 绿灯
以上就是状态模式的全部内容,感谢阅读。