备忘录模式:
不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样当需要时就可以很方便地将该对象恢复到原先保存的状态。简单的说就是通过一个备忘录来保存对象现有状态以便以后(调用备忘录)回滚到该状态。
适应于功能比较复杂的,需要维护、记录属性历史 的 类。
当角色改变的新状态无效时,可以使用备忘录将状态复原。
备忘录模式对其他对象屏蔽复杂对象的内部信息,从而保持封装的边界。
当时备忘录对象对内存有一定量的消耗,如果状态数据很大很多的话,所以还是要慎用的。
上图:
class Program
{
static void Main(string[] args)//言简意赅客户端
{
//大战前,初始状态
GameRole Cindy = new GameRole();
Cindy.GetInitState();
Cindy.StateDisplay();
//保存进度,封装在memento中不知道保存了哪些具体角色数据
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.Memento = Cindy.SaveState();//赋值保存
//大战boos
Cindy.Fight();
Cindy.StateDisplay();
//恢复之前状态,重来
Cindy.RecoveryState(stateAdmin.Memento);//之前赋的值导出
Cindy.StateDisplay();
Console.Read();
}
}
class Originator//发起人
{
private string state;
public string State//需要保存的属性
{
get{return state;}
set{state=value ;}
}
public Memento CreateMemento()//创建备忘录
{
//将信息导入并实例化出一个Memento
return (new Memento (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;}//需要保存的对象属性
}
}
#region 未加备忘录模式时,管理者为*
//class Caretaker//管理者类
//{
// private Memento memento;
// public Memento Memento//得到或设备备忘录
// {
// get{return memento ;}
// set{memento =value ;}
// }
//}
#endregion
//角色
class GameRole
{
//生命力
private int vit;
public int Virality
{
get { return vit; }
set { vit = value; }
}
//攻击力
private int atk;
public int Attack
{
get { return atk; }
set { atk = value; }
}
//防御力
private int def;
public int Defense
{
get { return def; }
set { def = value; }
}
//保存角色状态,状态值通过实例化“”返回
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;
}
public void StateDisplay()
{
Console.WriteLine("角色当前状态");
Console.WriteLine("体力{0}",this .vit );
Console.WriteLine("攻击力{0}",this .atk );
Console.WriteLine("防御力{0}",this .def );
Console.Read();
}
//初始状态
public void GetInitState()
{
this.vit = 100;
this.atk = 100;
this.def = 100;
}
public void Fight()//战斗
{
this.vit = 0;
this.atk = 0;
this.def = 0;
}
}
class RoleStateMemento//角色状态存储箱类
{
private int vit;
private int atk;
private int def;
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; }
}
public int Attack
{
get { return atk; }
set { atk = value; }
}
public int Defense
{
get { return def;}
set{ def=value ;}
}
}
class RoleStateCaretaker//角色状态管理类
{
private RoleStateMemento memento;
public RoleStateMemento Memento
{
get { return memento; }
set { memento = value; }
}
}