结构

状态模式

说明

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。

适用条件

  • 一个对象的行为取决于其状态, 并且它必须在运行时根据状态改变自己的行为。
  • 一个操作中包含大量的分支, 并且这些分支取决于对象的状态。

实现

public interface IState {

   void WriteName(StateContext stateContext, string name);

}

public class StateA : IState {
   
   public void WriteName(StateContext stateContext, string name) {
      Console.WriteLine(name.ToLower());
      stateContext.SetState(new StateB());
   }
}

public class StateB : IState {

   private int _count;

   public void WriteName(StateContext stateContext, string name) {
      Console.WriteLine(name.ToUpper());
      if (++this._count > 1) {
         stateContext.SetState(new StateA());
      }
   }
}

public class StateContext {
   
   private IState _state;

   public StateContext() {
      this._state = new StateA();
   }

   public void SetState(IState state) {
      this._state = state;
   }

   public void WriteName(string name) {
      this._state.WriteName(this, name);
   }
}

class Client {

   static void Main(string[] args) {
      var sc = new StateContext();
      sc.WriteName("Monday");
      sc.WriteName("Tuesday");
      sc.WriteName("Wednesday");
      sc.WriteName("Thursday");
      sc.WriteName("Saturday");
      sc.WriteName("Sunday");

      Console.ReadKey();
   }
}