当前位置: 编程技术>.net/c#/asp.net
c# 备忘录模式
来源: 互联网 发布时间:2014-10-15
本文导语: 结构图: Memento类:保存状态的容器 代码如下: class Memento { public string State { get; set; } public Memento(string state) { this.State = state; } }Caretaker是保存Memento类: 代...
结构图:
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();
}
}