继续整理记录这段时间来的收获,详细代码可在我的Gitee仓库Java设计模式克隆下载学习使用!
6.6 状态模式
6.6.1定义
对有状态的对象,把复杂的"判断逻辑"提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为
6.6.2 结构
- 环境角色:称上下文,定义了客户程序需要的接口,维护一个当前状态,并将与状态相关的操作委托给当前状态对象来处理
- 抽象状态角色:定义一个接口,用以封装环境对象中的特定状态所对应的行为
- 具体状态角色:实现抽象状态角色所对应的行为
6.6.3 案例(电梯状态)
- 环境角色
public class Context {
// 定义对应状态对象的常量
public final static OpeningState OPENING_STATE = new OpeningState();
public final static ClosingState CLOSING_STATE = new ClosingState();
public final static StopingState STOPING_STATE = new StopingState();
public final static RunningState RUNNING_STATE = new RunningState();
// 定义一个当前电梯状态变量
private LiftState liftState;
public void setLiftState(LiftState liftState) {
this.liftState = liftState;
// 设置当前状态对象中的Context对象
this.liftState.setContext(this);
}
public LiftState getLiftState() {
return liftState;
}
public void open() {
this.liftState.open();
}
public void close() {
this.liftState.close();