状态模式
一、定义:
当一个对象内在状态改变时允许改变行为,实现状态的改变
二、作用
主要解决的是当一个状态转换的条件表达式过于复杂的时候,把状态的判断转移到不同状态的一系列类中,把复杂的判断简单化
三、类图:
四、实现
1.work类 用于实现转换状态,状态判断,运行对应状态的程序 同时也是用户调用的接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Work { State state; public Work() { this.state = new Fornoon(); } private int hour; public int getHour() { return this.hour; } public void setHour(int hour) { this.hour = hour; } public void doWork() { this.state.doWork(this); } public void setState(State state) { this.state = state; } }
2.state类 实际运行的情况,调用work的状态切换
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public abstract class State { public abstract void doWork(Work work); }
3.state的实现类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Afternoon extends State { @Override public void doWork(Work work) { if(work.getHour() > 12) { System.out.println("in the afternoon"); } else { work.setState(new Fornoon()); work.doWork(); } } } public class Fornoon extends State { @Override public void doWork(Work work) { if(work.getHour() < 12) { System.out.println("in the morning"); } else { work.setState(new Afternoon()); work.doWork(); } } }
4.客户类 测试类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Client { public static void main(String[] args) { Work work = new Work(); work.setHour(14); work.doWork(); work.setHour(14); work.doWork(); } }