C#設計模式之:備忘錄模式
阿新 • • 發佈:2018-12-10
備忘錄模式(Memento)
在不破壞封裝性的前提下,捕獲一個物件的內部狀態,並在該物件之外儲存這個狀態。這樣以後就可將該物件恢復到原先儲存的狀態
UML
程式碼
class Memento
{
private string state;
public Memento(string state)
{
this.state = state;
}
public string State
{
get { return state; }
}
}
class Caretaker
{
private Memento memento;
internal Memento Memento { get => memento; set => memento = value; }
}
class Originator
{
private string state;
public string State { get => state; set => state = value; }
public Memento CreateMemento()
{
return new Memento(state);
}
public void SetMemento(Memento memento)
{
state = memento.State;
}
public void Show()
{
Console.WriteLine("State = " + state);
}
}
// test
Originator o = new Originator();
o.State = "On";
o.Show();
Caretaker c = new Caretaker();
c.Memento = o.CreateMemento();
o.State = "Off";
o.Show();
o.SetMemento(c.Memento);
o.Show();
// result
State = On
State = Off
State = On
說明
當需要儲存全部資訊時,可以考慮使用clone,但它會對上層應用開放了全部介面 而一般情況下,我們只需要儲存部分資訊,就可以使用備忘錄模式