1.状态模式
当一个对象的内在状态改变时允许改变其行为,这个对象看起像是改变了其类。
*状态模式主要解决的是当控制一个对象的状态转换的条件表达式过于复杂时,可以将状态的判断逻辑转移到表示不同状态的一系列类中,将复杂的判断逻辑简化。
*将特定与状态相关的行为局部化,并且将不同状态的行为分割开来。
*当一个对象的行为取决于它的状态,并且它必须运行时刻根据状态改它的行为时,就可以考虑状态模式。
namespace 状态模式{ class Program { static void Main(string[] args) { //一天开始 Work emergenvyProject = new Work(); emergenvyProject.Hour = 9; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 10; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 12; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 13; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 14; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 17; emergenvyProject.TaskFinshed = false; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 19; emergenvyProject.WriteProgram(); emergenvyProject.Hour = 22; emergenvyProject.WriteProgram(); Console.Read(); } } //状态的抽象接口 public abstract class State { public abstract void WriteProgram(Work w); } //状态类 public class ForenoonState : State { public override void WriteProgram(Work w) { if (w.Hour < 12) { Console.WriteLine("当前时间:{0}点,上午工作,精神百倍",w.Hour); } else { w.SetState(new NoonState()); w.WriteProgram(); } } } public class NoonState : State { public override void WriteProgram(Work w) { if (w.Hour < 13) { Console.WriteLine("当前时间:{0}点,中午累了,午休", w.Hour); } else { w.SetState(new AfternoonState()); w.WriteProgram(); } } } public class AfternoonState : State { public override void WriteProgram(Work w) { if (w.Hour < 17) { Console.WriteLine("当前时间:{0}点,下午状态还行,继续努力", w.Hour); } else { w.SetState(new EveningState());//实例化下个状态的类 w.WriteProgram(); //调用新类下的方法如此反复 } } } public class EveningState : State { public override void WriteProgram(Work w) { if (w.TaskFinshed) { w.SetState(new RestState()); w.WriteProgram(); } else { if (w.Hour < 21) { Console.WriteLine("当前时间:{0}点,加班ing", w.Hour); } else { w.SetState(new SleepingState()); w.WriteProgram(); } } } } public class SleepingState : State { public override void WriteProgram(Work w) { Console.WriteLine("当前时间:{0}点,睡着了", w.Hour); } } public class RestState : State { public override void WriteProgram(Work w) { Console.WriteLine("当前时间:{0}点,下班回家", w.Hour); } } //工作类 public class Work { private State current; public Work() { current = new ForenoonState(); } private double hour; public double Hour { get { return hour; } set { hour = value; } } private bool finish = false; public bool TaskFinshed { get { return finish; } set { finish = value; } } public void SetState(State s) { current = s; } public void WriteProgram() { current.WriteProgram(this); } }}