首页 > 代码库 > 备忘录模式
备忘录模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
备忘录模式
*/
namespace App_MYCS.HDL_SJMS.BWLMS
{
class my_BWLMS
{
public void dy()
{
originator o = new originator();
o.State = "on";
o.show();
Caretaer c = new Caretaer();
c.Memento = o.CreateMemento();
o.State = "off";
o.show();
o.SetMemento(c.Memento);
o.show();
}
}
//发起人
public class originator
{
private string state;
public string State
{
get { return state; }
set { state = value; }
}
public Memento CreateMemento()
{
return (new Memento(State));
}
public void SetMemento(Memento memento)
{
state = memento.State;
}
public void show()
{
Console.WriteLine("State="+state);
}
}
//备忘录
public class Memento
{
private string state;
public string State
{
get { return state; }
set { state = value; }
}
public Memento(string state)
{
this.state = state;
}
}
//管理者
class Caretaer
{
private Memento memento;
internal Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
//-------------------------------------------------------
//案例游戏存进度
//角色状态
class GameRoleState
{
private int vitality;//生命力
public int Vitality
{
get { return vitality; }
set { vitality = value; }
}
private int attack;//攻击力
public int Attack
{
get { return attack; }
set { attack = value; }
}
private int defense;//防御力
public int Defense
{
get { return defense; }
set { defense = value; }
}
public GameRoleState()
{
this.vitality = 100;
this.attack = 100;
this.defense = 100;
}
}
//状态存储箱
class RoleStateMemento
{
GameRoleState saveState;
//初始化并设置保存状态
public RoleStateMemento(GameRoleState savestate)
{
this.saveState = new GameRoleState();
}
//保存状态
public void SetSaveState(GameRoleState savestate)
{
this.saveState.Vitality = savestate.Defense;
this.saveState.Attack = savestate.Attack;
this.saveState.Defense = saveState.Defense;
}
//获取状态
public void GetSaveState(ref GameRoleState savestate)
{
savestate.Defense = this.saveState.Vitality;
savestate.Attack = this.saveState.Attack;
saveState.Defense = this.saveState.Defense;
}
}
class RoleStateCaretaker
{
private RoleStateMemento memento;
internal RoleStateMemento Memento
{
get { return memento; }
set { memento = value; }
}
}
//游戏角色
class GameRole
{
GameRoleState grs;
public GameRole()
{
grs = new GameRoleState();
}
public void GetGameRoleState()
{
//显示状态
Console.WriteLine("角色状态:生{0},攻{1},防{2}",grs.Vitality,grs.Attack,grs.Defense);
}
//保存状态
public RoleStateMemento SaveGameRolState()
{
return new RoleStateMemento(this.grs);
}
//恢复状态
public void RecoveryState(RoleStateMemento memento)
{
memento.GetSaveState(ref this.grs);
}
//大战
public void Fight()
{
this.grs.Vitality = 0;
this.grs.Attack = 0;
this.grs.Defense = 0;
}
}
class game_dyclass
{
public void dy()
{
GameRole gr = new GameRole();//初始化角色
gr.GetGameRoleState();//显示状态
//保存状态
RoleStateCaretaker rs = new RoleStateCaretaker();
rs.Memento = gr.SaveGameRolState();
//战死了
gr.Fight();
gr.GetGameRoleState();
//恢复状态
gr.RecoveryState(rs.Memento);
gr.GetGameRoleState();
}
}
}
备忘录模式