状态模式 开关灯 调用
LightStateContext lsc = new LightStateContext();
Task.Run(() =>
{
while (true)
{
lsc.Run();
Thread.Sleep(1000);
}
});
状态模式开关灯实现
class LightStateContext
{
BaseState CurrentState { set; get; }
public LightStateContext()
{
CurrentState = new LightOffState();
}
public void SetState(BaseState state)
{
CurrentState = state;
}
public BaseState GetState()
{
return CurrentState;
}
public void Run()
{
CurrentState.Turn(this);
}
}
abstract class BaseState
{
protected virtual bool CanToggleState()
{
return true;
}
public abstract void Turn(LightStateContext ctx);
}
class LightOnState : BaseState
{
public override void Turn(LightStateContext ctx)
{
if (CanToggleState())
{
Console.WriteLine($"light is on !");
ctx.SetState(new LightOffState());
}
}
}
class LightOffState : BaseState
{
public override void Turn(LightStateContext ctx)
{
Console.WriteLine($"light is off !");
ctx.SetState(new LightOnState());
}
}