标签:
状态模式(State),当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。
消除庞大的条件分支语句。状态模式通过把各种状态转移逻辑分布到State的子类之间,来减少相互间的依赖。
当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式了。
Demo1:
abstract class State { public abstract void Handle(Context context); }
class AState : State { public override void Handle(Context context) { context.State = new BState(); } }
class BState : State { public override void Handle(Context context) { context.State = new AState(); } }
class Context { private State state; public Context(State state) { this.state = state; } public State State { get { return state; } set { state = value; Console.WriteLine("当前状态:" + state.GetType().Name); } } public void Request() { state.Handle(this); } }
Test:
Context c = new Context(new AState()); c.Request(); c.Request(); c.Request(); c.Request();
Demo2:
abstract class State { public abstract void WriteProgram(Work w); }
class MorningState : State { public override void WriteProgram(Work w) { if (w.Hour < 12) { Console.WriteLine("当前时间:{0}点 上午工作,精神百倍", w.Hour); } else { w.SetState(new NoonState()); w.WriteProgram(); } } }
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(); } } }
class AfternoonState : State { public override void WriteProgram(Work w) { if (w.Hour < 17) { Console.WriteLine("当前时间:{0}点 下午状态不错,继续努力", w.Hour); } else { //w.SetState(new NoonState()); //w.WriteProgram(); Console.WriteLine("下班了"); } } }
class Work { private State current; public Work() { current = new MorningState(); } private double hour; public double Hour { get { return hour; } set { hour = value; } } private bool finish = false; public bool TaskFinished { get { return finish; } set { finish = value; } } public void SetState(State s) { current = s; } public void WriteProgram() { current.WriteProgram(this); } }
Test:
Work w = new Work(); w.WriteProgram(); w.Hour = 12; w.WriteProgram(); w.Hour = 13; w.WriteProgram(); w.Hour = 18; w.WriteProgram();
标签:
原文地址:http://www.cnblogs.com/laixiancai/p/4793245.html