应用场景:当有多个状态时,不同的状态对应不同的行为
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StateTest { class Program { static void Main(string[] args) { Context context = new Context(); context.SetState(new StateA());//设置初始状态 Console.WriteLine(context.GetState().ToString()); context.Next(); Console.WriteLine(context.GetState().ToString()); context.Next(); Console.WriteLine(context.GetState().ToString()); Console.Read(); } } interface IState { string ToString(); void Next(Context c); } class StateA : IState { public string ToString() { return "State A"; } public void Next(Context c) { c.SetState(new StateB()); } } class StateB : IState { public string ToString() { return "State B"; } public void Next(Context c) { c.SetState(new StateC()); } } class StateC : IState { public string ToString() { return "State C"; } public void Next(Context c) { c.SetState(new StateA()); } } class Context { private IState state; public IState GetState() { return state; } public void SetState(IState state) { this.state = state; } public void Next() { state.Next(this); } } }
运行效果