备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
备忘录模式结构图:
备忘录模式基本代码
发起人 Originator类
class Originator
{
//需要保存的属性,可能有多个
private string state;
public string State
{
get { return state;}
set { state = value;}
}
public Memento CreateMemento()
{
return (new Mementto(state));
}
public void SetMemento(Memento memento)
{
//恢复备忘录,将memento导放并将相关数据恢复
state = memento.State;
}
public void Show()
{
Console.WriteLine("State="+state);
}
}
class Memento
{
private string state;
public Memento(string state)
{
this.state = state;
}
public string State
{
get { return state;}
}
}
管理者类
class Caretaker
{
private Memento memento;
public Memento Memento
{
get { return memento;}
set { memento = value; }
}
}
---客户端代码---
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.Read();
}
保存的细节封装在Memento中,更改保存的细节也不用影响客户端
Memento 模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者城要保存的属性只是众多属性中的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。
游戏角色的备忘录实现(进度存盘)
class 游戏角色
{
//保存游戏角色
public RoleStateMemento SaveState()
{
return (new RoleStateMemento(vit,atk,def));
}
//恢复角色状态
public void RecoveryState(RoleStateMemento memento)
{
this.vit = memento.Vitality;
this.atk = memento.Attack;
this.def = memento.Defense;
}
}
//角色状态存储箱
class RoleStateMemento
{
private int vit
...
public RoleStateMemento(int vit,int atk,int def)
{
this.vit = vit;
this.atk = atk;
this.def = def;
}
//生命力
public int Vitality
{
get { return vit;}
set { vit = value;}
}
...
}
//角色状态管理者
class RoleStateCaretaker
{
private RoleStateMemento memento;
public RoleStateMemento Memento
{
get { return memento;}
set { memento = value;}
}
}
---客户端代码---
static void Main(string[] args)
{
//大战boss前
GameRole lixiaoyao = new GameRole();
lixiaoyao.GetInitState();
lixiaoyao.StateDisplay();
//保存进度
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.Memento = lixiaoyao.SaveState();
//大战boss时,损耗严重
lixiaoyao.Fight();
lixiaoyao.StateDisplay();
//恢复之前的状态
lixiaoyao.RecoveryState(stateAdmin.Memento);
lixiaoyao.StateDisplay();
Console.Read();
}