状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像时改变了其类。
namespace StateDesign { public abstract class State { public abstract void Handle(Context context); } public class ConcreteStateA : State { public override void Handle(Context context) { context.State=new ConcreteStateB(); } } public class ConcreteStateB : State { public override void Handle(Context context) { context.State = new ConcreteStateA(); } } public 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); } } }
测试代码:
StateDesign.Context c = new StateDesign.Context(new ConcreteStateA()); c.Request(); c.Request(); c.Request(); c.Request();