狀態模式(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); } } }View Code
測試代碼:
StateDesign.Context c = new StateDesign.Context(new ConcreteStateA()); c.Request(); c.Request(); c.Request(); c.Request();View Code