设计模式 - 13)状态模式
abstract class State
{
public abstract void WriteProgram(Work w);
}
class ForenoonState : State
{
public override void WriteProgram(Work w)
{
if (w.Hour < 12)
{
Console.WriteLine(string.Format("当前时间 {0} 点,working", w.Hour));
}
else
{
w.SetState(new NoonState());
w.WriteProgram();
}
}
}
class NoonState : State
{
public override void WriteProgram(Work w)
{
if (w.Hour < 13)
{
Console.WriteLine(string.Format("当前时间 {0} 点,sleep", w.Hour));
}
else
{
w.SetState(new AfterNoonState());
w.WriteProgram();
}
}
}
class AfterNoonState : State
{
public override void WriteProgram(Work w)
{
if (w.Hour < 17)
{
Console.WriteLine(string.Format("当前时间 {0} 点,working", w.Hour));
}
else
{
w.SetState(new EveningState());
w.WriteProgram();
}
}
}
class EveningState : State
{
public override void WriteProgram(Work w)
{
if (w.TaskFinished)
{
w.SetState(new RestState());
w.WriteProgram();
}
else
{
if (w.Hour < 21)
{
Console.WriteLine(string.Format("working at {0}", w.Hour));
}
else
{
w.SetState(new SleepState());
w.WriteProgram();
}
}
}
}
class RestState : State
{
public override void WriteProgram(Work w)
{
Console.WriteLine(string.Format("go home at {0}", w.Hour));
}
}
class SleepState :State
{
public override void WriteProgram(Work w)
{
Console.WriteLine(string.Format("sleep at {0}", w.Hour));
}
}
class Work
{
int _hour;
public int Hour
{
get { return _hour; }
set { _hour = value; }
}
bool _finish = false;
public bool TaskFinished
{
get { return _finish; }
set { _finish = value; }
}
/// <summary>
/// 当前状态
/// </summary>
State _current;
public void SetState(State st)
{
this._current = st;
}
public Work()
{
this._current = new ForenoonState();
}
/// <summary>
/// 执行状态对应的方法
/// </summary>
public void WriteProgram()
{
this._current.WriteProgram(this);
}
}
// 业务代码:
Work w = new Work();
w.Hour = 22;
w.WriteProgram();
抽象状态类定义每个状态需要实现的方法,然后继承抽象状态类的状态类都实现该方法;
定义一个 Context 类关联当前状态、设置当前状态、执行状态对应方法的方法。