📄 mementorealworld.cs
字号:
using System;
using System.Windows.Forms;
using System.Text;
//备忘录模式(Memento)
//意图
// 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
//适用性
// 1.必须保存一个对象在某一个时刻的(部分)状态, 这样以后需要时它才能恢复到先前的状态。
// 2.如果一个用接口来让其它对象直接得到这些状态,将会暴露对象的实现细节并破坏对象的封装性。
namespace DesignPattern.MementoRealWorld
{
class MementoRealWorld : AbstractPattern
{
public static void Run(TextBox tbInfo)
{
s_tbInfo = tbInfo;
s_tbInfo.Text = "";
SalesProspect s = new SalesProspect();
s.Name = "Noel van Halen";
s.Phone = "(412) 256-0990";
s.Budget = 25000.0;
// Store internal state
ProspectMemory m = new ProspectMemory();
m.Memento = s.SaveMemento();
// Continue changing originator
s.Name = "Leo Welch";
s.Phone = "(310) 209-7111";
s.Budget = 1000000.0;
// Restore saved state
s.RestoreMemento(m.Memento);
// Wait for user
//Console.Read();
}
}
// "Originator"
class SalesProspect
{
private string name;
private string phone;
private double budget;
// Properties
public string Name
{
get{ return name; }
set
{
name = value;
DesignPattern.FormMain.OutputInfo("Name: " + name);
}
}
public string Phone
{
get{ return phone; }
set
{
phone = value;
DesignPattern.FormMain.OutputInfo("Phone: " + phone);
}
}
public double Budget
{
get{ return budget; }
set
{
budget = value;
DesignPattern.FormMain.OutputInfo("Budget: " + budget);
}
}
public Memento SaveMemento()
{
DesignPattern.FormMain.OutputInfo("\nSaving state --\n");
return new Memento(name, phone, budget);
}
public void RestoreMemento(Memento memento)
{
DesignPattern.FormMain.OutputInfo("\nRestoring state --\n");
this.Name = memento.Name;
this.Phone = memento.Phone;
this.Budget = memento.Budget;
}
}
// "Memento"
class Memento
{
private string name;
private string phone;
private double budget;
// Constructor
public Memento(string name, string phone, double budget)
{
this.name = name;
this.phone = phone;
this.budget = budget;
}
// Properties
public string Name
{
get{ return name; }
set{ name = value; }
}
public string Phone
{
get{ return phone; }
set{ phone = value; }
}
public double Budget
{
get{ return budget; }
set{ budget = value; }
}
}
// "Caretaker"
class ProspectMemory
{
private Memento memento;
// Property
public Memento Memento
{
set{ memento = value; }
get{ return memento; }
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -