状态模式:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
Allow an object to alter its behavior when its internal state changes.The object will appear to change its class
类结构
环境类(Context): 定义客户感兴趣的接口。维护一个ConcreteState子类的实例,这个实例定义当前状态。
抽象状态类(State): 定义一个接口以封装与Context的一个特定状态相关的行为。
具体状态类(ConcreteState): 每一子类实现一个与Context的一个状态相关的行为。
代码:
/// <summary> /// 维护了当前状态的主体 /// </summary> public class StateContext { public StateContext() { } public StateContext(State state) { this.currentState = state; } private State currentState; public State CurrentState { set { currentState = value; } } /// <summary> /// 执行当前状态 /// </summary> public void Request() { currentState.Handle(this); } } public interface State { void Handle(StateContext stateContext); } /// <summary> /// 执行该状态对应的行为,设置下一个状态实例 /// </summary> public class ConcereteStateA : State { public void Handle(StateContext stateContext) { Console.WriteLine("状态A:处理行为执行了.....切换下一个状态B......"); stateContext.CurrentState = new ConcereteStateB(); } } /// <summary> /// 执行该状态对应的行为,设置下一个状态实例 /// </summary> public class ConcereteStateB : State { public void Handle(StateContext stateContext) { Console.WriteLine("状态B:处理行为执行了.....切换下一个状态A......"); stateContext.CurrentState = new ConcereteStateA(); } }
调用:
StateContext stateContext = new StateContext(new ConcereteStateA()); stateContext.Request(); stateContext.Request();
结果: