[設計模式練習]狀態模式
一年四季春夏秋冬用狀態模式設計
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.狀態
{
/// <summary>
/// 抽象類別:狀態
/// </summary>
public abstract class State
{
public abstract void WriteSeason(Season s);
}
/// <summary>
/// 實做狀態:春天
/// </summary>
public class Spring : State
{
public override void WriteSeason(Season s)
{
if (int.Parse(s.month) < 4 && int.Parse(s.month)>=1)
{
Console.WriteLine("春天到了");
}
else
{
s.SetState(new Summer());
s.WriteSeason();
}
}
}
/// <summary>
/// 實做狀態:夏天
/// </summary>
public class Summer : State
{
public override void WriteSeason(Season s)
{
if (int.Parse(s.month) < 7 && int.Parse(s.month)>=4)
{
Console.WriteLine("夏天到了");
}
else
{
s.SetState(new Fall());
s.WriteSeason();
}
}
}
/// <summary>
/// 實做狀態:秋天
/// </summary>
public class Fall : State
{
public override void WriteSeason(Season s)
{
if (int.Parse(s.month) < 10 && int.Parse(s.month) >= 7)
{
Console.WriteLine("秋天到了");
}
else
{
s.SetState(new Winter());
s.WriteSeason();
}
}
}
/// <summary>
/// 實做狀態:冬天
/// </summary>
public class Winter : State
{
public override void WriteSeason(Season s)
{
if (int.Parse(s.month) <= 12 && int.Parse(s.month) >= 10)
{
Console.WriteLine("冬天到了");
}
else
{
s.SetState(new Spring());
s.WriteSeason();
}
}
}
/// <summary>
/// 維護狀態子類別的實例,定義現在的狀態
/// </summary>
public class Season
{
//目前狀態
private State currentstate;
private string _month;
public Season()
{
//設定初始狀態為春天
currentstate = new Spring();
}
public string month
{
get { return _month; }
set { _month = value; }
}
/// <summary>
/// 設定目前狀態.
/// </summary>
/// <param name="inputstate">The inputstate.</param>
public void SetState(State inputstate)
{
currentstate = inputstate;
}
/// <summary>
/// 實現狀態子類別中要進行的動作:WriteSeason.
/// </summary>
public void WriteSeason()
{
currentstate.WriteSeason(this);
}
}
}
用戶端程式碼
//初始狀態為春天 狀態順序為春->夏->秋->冬->春....
DesignModelTest.狀態.Season currentseason = new DesignModelTest.狀態.Season();
currentseason.month = "1";
currentseason.WriteSeason();
currentseason.month = "4";
currentseason.WriteSeason();
currentseason.month = "8";
currentseason.WriteSeason();
currentseason.month = "10";
currentseason.WriteSeason();
currentseason.month = "3";
currentseason.WriteSeason();
Console.Read();
#endregion
輸出結果