设计模式(行为模式) 之 状态模式
事物有n种状态,且维护状态变化。
如:水有 固态、液态、气态 ;小于等于0度,0 到 100 度,等于100度时。
1)状态类 有共同的父接口,n个不同的状态实现类;
2)事物类中包含状态类父接口成员变量声明;
3)事物类中有一定的方法选择 当前处于何种状态;
以上述为例:
/**
* 水状态接口
* 气态 、 液态 、固态
*/
public interface IWaterState {
/**
* >100 气态
*/
int GAS = 100;
/**
* <0 固态
*/
int SOLID = 0;
// int liquid
public void goState();
}
public class GasWater implements IWaterState {
@Override
public void goState() {
System.out.println("气态");
}
}
public class LiquidWater implements IWaterState {
@Override
public void goState() {
System.out.println("液态");
}
}
public class SolidWater implements IWaterState {
@Override
public void goState() {
System.out.println("固态");
}
}
/**
* 降温 致 固态冰
*/
public class CoolWaterContext {
/**
* 度数
*/
private int num;
public CoolWaterContext(int num) {
if (num >= 100) {
this.num = 100;
} else {
this.num = num;
}
}
public void cool(int num) {
IWaterState waterState;
this.num = this.num - num;
if (this.num >= IWaterState.GAS) {
//气态
waterState = new GasWater();
} else if (IWaterState.SOLID < this.num && this.num < IWaterState.GAS) {
//液态
waterState = new LiquidWater();
} else {
//固态
waterState = new SolidWater();
}
waterState.goState();
}
}
/**
* 客户端调用
*/
public class Execute {
public static void main(String[] args) {
CoolWaterContext waterContext = new CoolWaterContext(100);
waterContext.cool(0);
waterContext.cool(99);
waterContext.cool(2);
}
}
结果: