模式介绍
备忘录模式就是在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。
示例
想象一下,一家真正高端的餐厅可能直接从当地农场订购,并且餐厅需要跟踪哪些配料来自哪些供应商。
在我们的系统中,我们需要跟踪关于特定供应商输入的信息量,并且如果我们意外地输入了错误的地址,就能够将信息恢复到以前的状态。
/// <summary>
/// The Originator class, which is the class for which we want to save Mementos for its state.
/// </summary>
class FoodSupplier
{
private string _name;
private string _phone;
private string _address;
public string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine("Proprietor: " + _name);
}
}
public string Phone
{
get { return _phone; }
set
{
_phone = value;
Console.WriteLine("Phone Number: " + _phone);
}
}
public string Address
{
get { return _address; }
set
{
_address = value;
Console.WriteLine("Address: " + _address);
}
}
public FoodSupplierMemento SaveMemento()
{
Console.WriteLine("
Saving current state
");
return new FoodSupplierMemento(_name, _phone, _address);
}
public void RestoreMemento(FoodSupplierMemento memento)
{
Console.WriteLine("
Restoring previous state
");
Name = memento.Name;
Phone = memento.PhoneNumber;
Address = memento.Address;
}
}
备忘录类:
/// <summary>
/// The Memento class
/// </summary>
class FoodSupplierMemento
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public FoodSupplierMemento(string name, string phone, string address)
{
Name = name;
PhoneNumber = phone;
Address = address;
}
}
守护者类:
/// <summary>
/// The Caretaker class. This class never examines the contents of any Memento and is
/// responsible for keeping that memento.
/// </summary>
class SupplierMemory
{
private FoodSupplierMemento _memento;
public FoodSupplierMemento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
客户端调用:
static void Main(string[] args)
{
//Here's a new supplier for our restaurant
FoodSupplier s = new FoodSupplier();
s.Name = "Harold Karstark";
s.Phone = "(482) 555-1172";
// Let's store that entry in our database.
SupplierMemory m = new SupplierMemory();
m.Memento = s.SaveMemento();
// Continue changing originator
s.Address = "548 S Main St. Nowhere, KS";
// Crap, gotta undo that entry, I entered the wrong address
s.RestoreMemento(m.Memento);
Console.ReadKey();
}
总结
备忘录模式试图将对象的状态封装为另一个对象(称为Memento),并允许从该Memento恢复对象的状态。
源代码
https://github.com/exceptionnotfound/DesignPatterns/tree/master/Memento
原文
https://www.exceptionnotfound.net/the-daily-design-pattern-memento/