基本定義ide
備忘錄模式:在不破壞封裝性的前提下,捕獲一個對象的內部狀態,並在該對象以外保存這個狀態。這樣之後就能夠將該對象恢復到原先保存的狀態。this
解釋:簡單來講,就是保存一個對象在某一時刻的特定狀態,在之後須要的時候能夠將對象恢復到保存時的狀態。spa
基本代碼:code
class Originator { private string state; public string State { get { return state; } set { state = value; } } public Memento CreateMemento() { return new Memento(state); } public void SetMemento(Memento memento) { state = memento.State; } public void Display() { Console.WriteLine("State=" + state); } } class Memento { private string state; public string State { get { return state; } } public Memento(string state) { this.state = state; } } class Caretaker { private Memento memento1; public Memento Memento1 { get { return memento1; } set { memento1 = value; } } }
客戶端調用:對象
Originator originator = new Originator(); originator.State = "on"; originator.Display(); Caretaker caretaker = new Caretaker(); caretaker.Memento1 = originator.CreateMemento(); originator.State = "off"; originator.Display(); originator.SetMemento(caretaker.Memento1); originator.Display();
列舉具體實例:blog
打遊戲,保存一角色在打boss前的狀態,待打boss結束後再恢復到它以前的狀態。遊戲
class Program { static void Main(string[] args) { Role role = new Role(100, 100); Console.WriteLine("大戰前:"); role.Display(); Caretaker caretaker = new Caretaker(); caretaker.memento = role.SaveMemento(); role.SetBloodFlow(20); role.SetMagicPoint(20); Console.WriteLine("大戰"); role.Display(); role.RestoreMemento(caretaker.GetMemento()); Console.WriteLine("恢復"); role.Display(); Console.Read(); } } class Role { private int bloodFlow; private int magicPoint; public Role(int bloodFlow, int magicPoint) { this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } public int GetBloodFlow() { return bloodFlow; } public void SetBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int GetMagicPoint() { return magicPoint; } public void SetMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } public void Display() { Console.WriteLine("用戶當前的狀態:"); Console.WriteLine("血量:" + GetBloodFlow() + ";藍量:" + GetMagicPoint()); } public Memento SaveMemento() { return new Memento(GetBloodFlow (),GetMagicPoint ()); } public void RestoreMemento(Memento memento) { this.bloodFlow = memento.GetBloodFlow(); this.magicPoint = memento.GetMagicPoint(); } } class Memento { private int bloodFlow; private int magicPoint; public Memento(int bloodFlow, int magicPoint) { this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } public int GetBloodFlow() { return bloodFlow; } public void SetBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int GetMagicPoint() { return magicPoint; } public void SetMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } } class Caretaker { public Memento memento; public Memento GetMemento() { return memento; } public void SetMemento(Memento memento) { this.memento = memento; } }
備忘錄模式的優缺點及適用場景:內存
優勢:資源
爲用戶提供一種能夠恢復狀態的機制,用戶比較方便的恢復到某個歷史狀態。get
隱藏恢復細節,用戶不須要關心狀態的保存細節。
缺點:
對象狀態須要完整存儲到備忘錄對象中,若是狀態數據很大,那麼在資源消耗上,備忘錄對象會很是耗內存。
適用場景:
簡單來講,顯現其優勢迴避其缺點的地方均可以使用備忘錄模式。