定义:在不破坏封装的前提下,捕获并且保存一个对象的内部状态,这样可以将对象恢复到原先保存的状态。正如很多软件中,按Ctrl-Z会取消最后一次用户操作,即撤销(Undo)操作。
一般情况下,备忘录模式有三个类:
Memento:备忘录; Originator:原发器; Caretaker:看管者,负责看管备忘录。
using System;
using System.Collections.Generic;
using System.Text;
namespace 备忘录_游戏存进度
{
class GameRole
{
private int vit;//生命力
public int Vit
{
get { return vit; }
set { vit = value; }
}
private int atk;//攻击力
public int Atk
{
get { return atk; }
set { atk = value; }
}
private int def;//防御力
public int Def
{
get { return def; }
set { def = value; }
}
public Memento SaveMemento()//保存内部状态
{
return (new Memento(vit, atk, def));
}
public void RestoreMemento(Memento memento)//恢复状态
{
this.vit = memento.Vit;
this.atk = memento.Atk;
this.def = memento.Def;
}
public void Show()
{
Console.WriteLine("角色当前状态:");
Console.WriteLine("生命力:{0}",this.vit);
Console.WriteLine("攻击力:{0}", this.atk);
Console.WriteLine("防御力:{0}", this.def);
}
}
class Memento
{
private int vit;//生命力
public int Vit
{
get { return vit; }
set { vit = value; }
}
private int atk;//攻击力
public int Atk
{
get { return atk; }
set { atk = value; }
}
private int def;//防御力
public int Def
{
get { return def; }
set { def = value; }
}
public Memento(int vit, int atk, int def)
{
this.vit = vit;
this.atk = atk;
this.def = def;
}
}
class Caretaker
{
private Memento memento;
public Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
class Program
{
static void Main(string[] args)
{
GameRole g = new GameRole();
g.Vit = 100;
g.Atk= 100;
g.Def = 100;
g.Show();
Caretaker c = new Caretaker();
c.Memento = g.SaveMemento();
g.Vit = 200;
g.Atk = 200;
g.Def = 200;
g.Show();
g.RestoreMemento(c.Memento);
g.Show();
Console.Read();
}
}
}
如果要实现多次Undo(撤销)或Ctrl-Z,只需将Caretaker类里的单个备忘录改成备忘录向量即可。恢复时每次取向量里最后一个的元素用于恢复。