标签:style class blog code ext color
*状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂的时候,吧状态判断逻辑独立到一系列的类中,
是复杂的逻辑简单化。
Work work = new Work(); work.Hour = 10; work.WriteProgram(); work.Hour = 13; work.WriteProgram(); work.Hour = 16; work.WriteProgram(); work.Hour = 25; work.WriteProgram(); /// <summary> /// 抽象状态 /// </summary> public abstract class StateJob { public abstract void WriteProgram(Work work); } //具体状态 public class ForenoonState : StateJob { public override void WriteProgram(Work work) { if (work.Hour < 12) Console.WriteLine("当前时间:‘{0}‘,上午工作时间", work.Hour); else { work.SetState(new RestState()); work.WriteProgram(); } } } //具体状态 public class RestState : StateJob { public override void WriteProgram(Work work) { if (work.Hour < 14) Console.WriteLine("当前时间:‘{0}‘,午休时间", work.Hour); else { work.SetState(new AfternoonState()); work.WriteProgram(); } } } //具体状态 public class AfternoonState : StateJob { public override void WriteProgram(Work work) { if (work.Hour < 18) Console.WriteLine("当前时间:‘{0}‘,下午工作时间", work.Hour); else { work.SetState(new SleepState()); work.WriteProgram(); } } } //具体状态 public class SleepState : StateJob { public override void WriteProgram(Work work) { Console.WriteLine("当前时间:‘{0}‘,睡觉时间",work.Hour); } } //工作类 public class Work { public int Hour { get; set; } public bool finish { get; set; } private StateJob current;
//初始状态 public Work() { current = new ForenoonState(); } public void SetState(StateJob s) { current = s; } public void WriteProgram() { current.WriteProgram(this); } }
Context c = new Context(new ConStateB()); c.Request(); c.Request(); c.Request(); /// <summary> /// 抽象状态 /// </summary> public abstract class State { public abstract void Handel(Context context); } /// <summary> /// 具体状态 ConcreteSate /// </summary> public class ConStateA : State { public override void Handel(Context context) { context.State = new ConStateB(); } } /// <summary> /// 具体状态 /// </summary> public class ConStateB : State { public override void Handel(Context context) { context.State = new ConStateA(); } } /// <summary> /// 维护一个ConcreteSate子类 /// </summary> public class Context { private State state; public Context(State _state) { this.state = _state; } public State State { get; set; } public void Request() { Console.WriteLine("当前状态:‘{0}‘", state.GetType().Name); state.Handel(this); } }
标签:style class blog code ext color
原文地址:http://www.cnblogs.com/dragon-L/p/3785966.html