标签:
状态模式是解决一种固定循环的问题。
例如:交通灯这样的。绿 黄 红 按顺序执行的问题。
1、Context 类
public class Context { private BaseLight Light = null; public Context(BaseLight light) { Light = light; } public void Change() { Light.Change(this); } public void Set(BaseLight light) { Light = light; // Light.Change(); } }
2、抽像的 BaseLight 类
public abstract class BaseLight { public Light LightState { get; private set; } public BaseLight(Light state) { LightState = state; } public abstract void Change(Context context); }
3、信号灯类:GreenLight、RedLight、YellowLight
public class YellowLight : BaseLight { public YellowLight() : base(Light.Yellow) { } public override void Change(Context context) { Console.WriteLine("当前灯的颜色是:{0},Change", this.GetType()); context.Set(new RedLight()); } } public class RedLight : BaseLight { public RedLight() : base(Light.Red) { } public override void Change(Context context) { Console.WriteLine("当前灯的颜色是:{0},Change", this.GetType()); context.Set(new GreenLight()); } } public class GreenLight : BaseLight { public GreenLight() : base(Light.Green) { } public override void Change(Context context) { Console.WriteLine("当前灯的颜色是:{0},Change", this.GetType()); context.Set(new YellowLight()); } }
4、使用:
Context context = new Context(new GreenLight()); context.Change(); context.Change(); context.Change(); context.Change(); context.Change(); context.Change(); Console.ReadLine();
5、运行结果:
标签:
原文地址:http://www.cnblogs.com/lystory/p/5693952.html