# 状态模式
属于行为型模式。
允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。
在面临大量的 if else 语句时,使用状态模式可以消除这些 if else 语句,并且可以封装变化点,新增条件和状态时,只需要在原来的基础上进行扩展即可。
在有限状态机中使用了这种模式。
# 类图
# 代码
# 状态类
| namespace BehavioralPatterns_StatePattern |
| { |
| |
| |
| |
| public abstract class State |
| { |
| |
| |
| |
| public ITrigger Trigger; |
| |
| |
| |
| |
| public abstract void EnterState(); |
| } |
| } |
| namespace BehavioralPatterns_StatePattern |
| { |
| public class State_1 : State |
| { |
| public State_1() |
| { |
| Trigger = new Trigger_1(); |
| } |
| |
| public override void EnterState() |
| { |
| Console.WriteLine("State_1"); |
| } |
| } |
| } |
| namespace BehavioralPatterns_StatePattern |
| { |
| public class State_0 : State |
| { |
| public State_0() |
| { |
| Trigger = new Trigger_0(); |
| } |
| |
| public override void EnterState() |
| { |
| Console.WriteLine("State_0"); |
| } |
| } |
| } |
# 条件类
| namespace BehavioralPatterns_StatePattern |
| { |
| |
| |
| |
| public interface ITrigger |
| { |
| |
| |
| |
| |
| public State HandleTrigger(StateController control); |
| } |
| } |
| namespace BehavioralPatterns_StatePattern |
| { |
| public class Trigger_0 : ITrigger |
| { |
| public State HandleTrigger(StateController control) |
| { |
| if (control.Time >= 10) |
| { |
| return new State_1(); |
| } |
| return control.CurrentState; |
| } |
| } |
| } |
| namespace BehavioralPatterns_StatePattern |
| { |
| public class Trigger_1 : ITrigger |
| { |
| public State HandleTrigger(StateController control) |
| { |
| if (control.Time < 10) |
| { |
| return new State_0(); |
| } |
| return control.CurrentState; |
| } |
| } |
| } |
# 状态控制类
| namespace BehavioralPatterns_StatePattern |
| { |
| |
| |
| |
| public class StateController |
| { |
| |
| |
| |
| public State CurrentState; |
| |
| |
| |
| public ITrigger CurrentTrigger; |
| |
| |
| |
| |
| public float Time; |
| |
| public StateController() |
| { |
| |
| Time = 0; |
| CurrentState = new State_0(); |
| CurrentTrigger = CurrentState.Trigger; |
| } |
| |
| |
| |
| |
| public void StateAction() |
| { |
| CurrentState.EnterState(); |
| } |
| |
| |
| |
| |
| public void ChangeState() |
| { |
| while (true) |
| { |
| CurrentState = CurrentTrigger.HandleTrigger(this); |
| CurrentTrigger = CurrentState.Trigger; |
| Thread.Sleep(100); |
| } |
| } |
| } |
| } |
# 测试
| namespace BehavioralPatterns_StatePattern |
| { |
| public class Program |
| { |
| private static void Main() |
| { |
| StateController stateController = new StateController(); |
| |
| Thread thread = new Thread(stateController.ChangeState); |
| thread.Start(); |
| |
| stateController.StateAction(); |
| |
| stateController.Time = 12; |
| Thread.Sleep(500); |
| |
| stateController.StateAction(); |
| |
| thread.Abort(); |
| } |
| } |
| } |