首页 > 学院 > 开发设计 > 正文

状态模式

2019-11-08 02:21:32
字体:
来源:转载
供稿:网友
 class OldWork{     public int getHour() {         return hour;     }     public void setHour(int hour) {         this.hour = hour;     }     PRivate int hour;     public void WriteProgram(){         if(hour<12){           System.out.println("forenoon ,good!");         }else if(hour<13){           System.out.println("need sleep!");         }else if(hour<17){           System.out.println("afernoon,go on!");         }     }  }
在没有使用状态模式时,会出现大量的if  else语句。使用后:
 class  Work{      private  State current;      public void setCurrent(State current) {          this.current = current;      }      public Work(){ current=new ForenoonState();}      public int getHour() {          return hour;      }      public void setHour(int hour) {          this.hour = hour;      }      private int hour;      public void WriteProgram(){          current.WriteProgram(this);      }  }  abstract class State{      public abstract void WriteProgram(Work w);  }  class ForenoonState extends State{       public void WriteProgram(Work w){        if(w.getHour()<12){            System.out.println("forenoon ,good!");        }       else{            w.setCurrent(new NoonState());w.WriteProgram();        }      }  }class NoonState extends State{    public void WriteProgram(Work w){        if(w.getHour()<13){            System.out.println("need sleep!");        }        else{            w.setCurrent(new AfternoonState());w.WriteProgram();        }    }}class AfternoonState extends State{    public void WriteProgram(Work w){        if(w.getHour()<17){            System.out.println("afernoon,go on!");        }        else{            System.out.println("go home,tired!");        }    }}
测试代码:
public class TestState {  public static void main(String[] args){     Work work=new Work();      work.setHour(12);      work.WriteProgram();  }}输出:need sleep!
状态模式:当一个对象的内在状态改变时允许改变其行为。这个对象看起来像是改变了其类。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表