c# 备忘录模式
作者:
备忘录模式:在不破坏封装的前提下,捕获一个对象的内部状态,并在这个对象之外的地方保存这个状态,这样以后就可将该对象恢复到原来保存的状态了
结构图:
Memento类:保存状态的容器
class Memento
{
public string State { get; set; }
public Memento(string state)
{
this.State = state;
}
}
Caretaker是保存Memento类:
class Caretaker
{
public Memento Memento { get; set; }
}
Originator类就是需要保存状态的类:
class Originator
{
public string State { get; set; }
public Memento CreateMemento()
{
return (new Memento(State));
}
public void SetMemento(Memento memento)
{
State = memento.State;
}
public void Show()
{
Console.WriteLine("State:" + State);
}
}
主函数调用:
class Program
{
static void Main(string[] args)
{
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();
}
}
Memento类:保存状态的容器
复制代码 代码如下:
class Memento
{
public string State { get; set; }
public Memento(string state)
{
this.State = state;
}
}
Caretaker是保存Memento类:
复制代码 代码如下:
class Caretaker
{
public Memento Memento { get; set; }
}
Originator类就是需要保存状态的类:
复制代码 代码如下:
class Originator
{
public string State { get; set; }
public Memento CreateMemento()
{
return (new Memento(State));
}
public void SetMemento(Memento memento)
{
State = memento.State;
}
public void Show()
{
Console.WriteLine("State:" + State);
}
}
主函数调用:
复制代码 代码如下:
class Program
{
static void Main(string[] args)
{
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();
}
}