你的位置:首页 > ASP.net教程

[ASP.net教程]《大话设计模式》学习笔记12:状态模式


  

工作状态示例:

  

1.State:

  public abstract class State  {    public abstract void WriteProgram(Work work);  }

2.ConcreteState(以ForenoonState、NoonState、SleepingState为例):

  public class ForenoonState:State  {    public override void WriteProgram(Work work)    {      if(work.Hour<12)      {        Console.WriteLine("当前时间:{0} 上午工作,精神百倍", work.Hour);      }      else      {        work.SetState(new NoonState());        work.WriteProgram();      }    }  }

  public class NoonState:State  {    public override void WriteProgram(Work work)    {      if(work.Hour<13)      {        Console.WriteLine("当前时间:{0} 饿了,午饭;犯困,午休", work.Hour);      }      else      {        work.SetState(new AfterNoonState());        work.WriteProgram();      }    }  }

  public class SleepingState:State  {    public override void WriteProgram(Work work)    {      Console.WriteLine("当前时间:{0} 太困了,睡着了", work.Hour);    }  }

3.Content:

  public class Work  {    private State state;    public Work()    {      state = new ForenoonState();    }    public int Hour { get; set; }    public void SetState(State state)    {      this.state = state;    }    public void WriteProgram()    {      state.WriteProgram(this);    }  }

4.客户端代码:

  class Program  {    static void Main(string[] args)    {      Work work = new Work();      work.Hour = 9;      work.WriteProgram();      work.Hour = 12;      work.WriteProgram();      work.Hour = 19;      work.WriteProgram();    }  }

 

  状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。