备忘录(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象外保存这个状态。这样就可将该对象恢复到原先保存的状态。
1、Originator(发起人):负责创建一个Memento备忘录,用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。Originator可根据需要决定Memento存储 Originator的哪些内部状态。
2、 Memento(备忘录):负责存储Originator内部状态,并可防止Originator以外的对象访问备忘录Memento。备忘录有两个接口,Caretaker只能看到备忘录的窄接口,它只能将备忘录传递给其他对象。Originator能看到一个粗接口,允许它访问返回到先前状态的所有数据。
备忘录模式代码
using System;
using System.Collections.Generic;
using System.Text;
namespace Memento
{
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.ReadLine();
}
}
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 Show()
{
Console.WriteLine("State="+State);
}
}
class Memento
{
private string _state;
public string State
{
get { return _state; }
set { _state = value; }
}
public Memento(string state)
{
this._state = state;
}
}
class Caretaker
{
private Memento memento;
internal Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Memento
{
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.ReadLine();
}
}
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 Show()
{
Console.WriteLine("State="+State);
}
}
class Memento
{
private string _state;
public string State
{
get { return _state; }
set { _state = value; }
}
public Memento(string state)
{
this._state = state;
}
}
class Caretaker
{
private Memento memento;
internal Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
}