概念:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
核心:主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中。
状态模式结构图
java代码:
public class StateTest {
public static void main(String[] args) {
Work work = new Work(new NoonState());
work.Hour = 10;
work.WriteProgram();
work.Hour = 17;
work.WriteProgram();
work.Hour = 22;
work.WriteProgram();
}
}
public class Work {
int Hour;
boolean finfish;
State state;
public Work(State state) {
this.state = state;
}
public void WriteProgram(){
state.writeProgram(this);
}
}
public abstract class State {
public abstract void writeProgram(Work w);
}
public class ForenoonState extends State {
@Override
public void writeProgram(Work w) {
if (w.Hour < 12){
System.out.println("当前时间: " + w.Hour + ",精神百倍, 努力工作");
}else{
w.state = new NoonState();
w.state.writeProgram(w);
}
}
}
public class NoonState extends State{
@Override
public void writeProgram(Work w) {
if (w.Hour < 20){
System.out.println("下午时间"+ w.Hour +"有点犯困");
}else{
w.state = new AfternoonState();
w.state.writeProgram(w);
}
}
}
public class AfternoonState extends State {
@Override
public void writeProgram(Work w) {
if (w.Hour < 24){
System.out.println("晚上时间"+ w.Hour +"加班严重");
}else{
System.out.println("等着猝死");
}
}
}