1. 程式人生 > 實用技巧 >設計模式 - 13)狀態模式

設計模式 - 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 類關聯當前狀態、設定當前狀態、執行狀態對應方法的方法。