備忘錄模式:在不破壞封裝前提下,捕獲物件內部狀態並外部化儲存,以便日後恢復。
系統功能複雜需記錄歷史屬性以支援回復操作。Originator 根據 Memento 還原先前狀態。

CreateMemento() 建立備忘錄、SetMemento() 恢復狀態、Show() 顯示狀態。決定備忘錄儲存哪些狀態。public class Originator {
private string _state;
public string State { get => _state; set => _state = value; }
public Memento CreateMemento() => new Memento(this.State);
public void SetMemento(Memento m) => this.State = m.State;
public void Show() => Console.WriteLine($"當前狀態: {this.State}");
}
public class Memento {
public string State { get; set; }
public Memento(string state) => State = state;
}
public class Caretaker {
public Memento Memento { get; set; }
}
static void Main() {
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(); // 恢復
Console.ReadKey();
}


SaveMemento()/RestoreMemento()。class SalesProspect {
private string _name, _phone; private double _budget;
public string Name { get=>_name; set{_name=value; Console.WriteLine("Name: "+_name);} }
public string Phone { get=>_phone; set{_phone=value; Console.WriteLine("Phone: "+_phone);} }
public double Budget { get=>_budget; set{_budget=value; Console.WriteLine("Budget: "+_budget);} }
public Memento SaveMemento() { Console.WriteLine("\nSaving state --\n"); return new Memento(_name,_phone,_budget); }
public void RestoreMemento(Memento m) { Console.WriteLine("\nRestoring state --\n"); Name=m.Name; Phone=m.Phone; Budget=m.Budget; }
}
class Memento {
public string Name {get;set;} public string Phone {get;set;} public double Budget {get;set;}
public Memento(string n,string p,double b){Name=n;Phone=p;Budget=b;}
}
class ProspectMemory { public Memento Memento {get;set;} }
static void Main() {
SalesProspect s = new SalesProspect();
s.Name = "Noel van Halen"; s.Phone = "(412) 256-0990"; s.Budget = 25000;
ProspectMemory m = new ProspectMemory(); m.Memento = s.SaveMemento();
s.Name = "Leo Welch"; s.Phone = "(310) 209-7111"; s.Budget = 1000000;
s.RestoreMemento(m.Memento); // 回復 Noel
Console.ReadKey();
}

備忘錄模式實現狀態外部化儲存與恢復,核心三角色分工明確,適用於撤銷/重做、檢查點恢復等場景。