[設計模式練習]備忘錄模式
將男生女生分成認識和不認識利用備忘錄模式設計(有點差=.=)
初始狀態為不認識
在認識後可以回復初始狀態(這倒是真的 翻臉比翻書還快=.=)
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.備忘錄
{
/// <summary>
/// 發起人:關係
/// </summary>
class Relation
{
private string man;//男生姓名
private string woman;//女生姓名
private string relation;//關係
public Relation(string manName, string womanName)
{
this.man = manName;
this.woman = womanName;
}
/// <summary>
/// 初始狀態不認識.
/// </summary>
public void initial()
{
this.relation = "不認識";
}
/// <summary>
/// 認識.
/// </summary>
public void knowing()
{
this.relation = "認識";
}
/// <summary>
/// 顯示目前關係.
/// </summary>
public void DisplayRelation()
{
Console.WriteLine(this.man + "\t" + this.relation + "\t" + this.woman);
}
/// <summary>
/// 儲存狀態.
/// </summary>
/// <returns></returns>
public Memento SaveState()
{
return (new Memento(this.relation));
}
/// <summary>
/// 回復狀態.
/// </summary>
/// <param name="memento">The memento.</param>
public void RecoveryState(Memento memento)
{
this.relation = memento.state;
}
}
/// <summary>
/// 備忘錄:負責儲存發起人的內部狀態
/// </summary>
class Memento
{
private string _state;
public Memento(string state)
{
this._state = state;
}
public string state
{
get { return _state; }
}
}
/// <summary>
/// 管理者:負責保存好備忘錄
/// </summary>
class Caretaker
{
public Memento _memento;
}
}
用戶端程式碼
DesignModelTest.備忘錄.Relation r1 = new DesignModelTest.備忘錄.Relation("男生", "女生");
r1.initial();//初始狀態為不認識
r1.DisplayRelation();
DesignModelTest.備忘錄.Caretaker c1 = new DesignModelTest.備忘錄.Caretaker();
c1._memento = r1.SaveState();//存入資訊(初始狀態為不認識)
r1.knowing();//將狀態改為認識
r1.DisplayRelation();
r1.RecoveryState(c1._memento);//回復資訊為不認識
r1.DisplayRelation();
Console.Read();
#endregion
輸出結果