public abstract class State { public abstract void Handle(Context context); } public class ConcreteStateA : State { public override void Handle(Context context) { context.State = new ConcreteStateB(); } } public class ConcreteStateB : State { public override void Handle(Context context) { context.State = new ConcreteStateA(); } } public class Context { private State _state; public Context(State state) { this._state = state; } public State State { get { return _state; } set { _state = value;} } public void Request() { _state.Handle(this); } } /// <summary> /// 客户端程序 /// </summary> class Program { static void Main(string[] args) { Context context = new Context(new ConcreteStateA()); context.Request(); context.Request(); context.Request(); } }
public abstract class State { public abstract void Change(ChangeLightState c); } public class OnState : State { public override void Change(ChangeLightState c) { c.State = new OffState(); } } public class OffState : State { public override void Change(ChangeLightState c) { c.State = new OnState(); } } public class ChangeLightState { public State State { get; set; } public void Change() { State.Change(this); } }
/// <summary> /// 客户端程序 /// </summary> class Program { static void Main(string[] args) { ChangeLightState c = new ChangeLightState(); c.State = new OnState(); c.Change(); c.Change(); c.Change(); } }