定義:在不破壞封裝的前提下,捕獲並且保存一個對象的內部狀態,這樣可以將對象恢復到原先保存的狀態。正如很多軟件中,按Ctrl-Z會取消最後一次用戶操作,即撤銷(Undo)操作。
一般情況下,備忘錄模式有三個類:
Memento:備忘錄; Originator:原發器; Caretaker:看管者,負責看管備忘錄。
[csharp]
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類裡的單個備忘錄改成備忘錄向量即可。恢復時每次取向量裡最後一個的元素用於恢復。