您的位置:首页 > 其它

设计模式之备忘录模式

2010-11-19 13:44 411 查看
备忘录模式:当对象的状态需要回到前面某个状态时,可以通过备忘录模式,定义需要保存的细节的类,对需要保存的细节进行保存。这样,当需要保存的细节变化时,也不会影响到客户端

#region 备忘录模式

/// <summary>
/// 备忘类,需要保存的数据集合
/// </summary>
class GameRoleMemento
{
private int atk;   //攻击力
private int def;   //防御力
private int vit;   //生命力
public int Vitality
{
set { vit = value; }
get { return vit; }
}

public int Attack
{
set { atk = value; }
get { return atk; }
}
public int Defense
{
set { def = value; }
get { return def; }
}
public GameRoleMemento(int atk, int def, int vit)
{
this.atk = atk;
this.def = def;
this.vit = vit;
}
}

/// <summary>
/// 角色状态管理类,负责管理备忘类
/// </summary>
class GameRoleCareTaker
{
private GameRoleMemento _gameRoleMemento;
public GameRoleMemento Memento
{
set { _gameRoleMemento = value; }
get { return _gameRoleMemento; }
}
}

/// <summary>
/// 游戏角色类
/// </summary>
class GameRole
{
private string gameTitle;
private string name;
private int atk;   //攻击力
private int def;   //防御力
private int vit;   //生命力

public string GameTitle
{
set { gameTitle = value; }
get { return gameTitle; }
}
public string Name
{
set { name = value; }
get { return name; }
}

public int Vitality
{
set { vit = value; }
get { return vit; }
}

public int Attack
{
set { atk = value; }
get { return atk; }
}
public int Defense
{
set { def = value; }
get { return def; }
}

public GameRole(string gameTitle, string name)
{
this.gameTitle = gameTitle;
this.name = name;
}
public GameRoleMemento SaveGameData()
{
return new GameRoleMemento(atk, def, vit);
}

public void RecoveryGameRole(GameRoleMemento gameRoleMemento)
{
this.vit = gameRoleMemento.Vitality;
this.def = gameRoleMemento.Defense;
this.atk = gameRoleMemento.Attack;
}

public void GetInitialData()
{
this.vit = 100;
this.def = 100;
this.atk = 100;
}

public void Fight()
{
this.vit = Convert.ToInt32(this.vit * 0.8);
this.def = Convert.ToInt32(this.def * 0.5);
this.atk = Convert.ToInt32(this.atk * 0.9);
}

public void DisplayData()
{
Console.WriteLine("{0}角色{1}当前状态值:", gameTitle, name);
Console.WriteLine("生命值:{0}", this.vit);
Console.WriteLine("攻击力:{0}", this.atk);
Console.WriteLine("防御力:{0}", this.def);
}

}
#endregion

class Program
{
static void Main(string[] args)
{
#region 备忘录模式
Console.WriteLine("备忘录模式效果演示:");
GameRole 韩菱纱 = new GameRole("仙剑四", "韩菱纱");
韩菱纱.GetInitialData();
韩菱纱.DisplayData();
GameRoleCareTaker c = new GameRoleCareTaker();
c.Memento = 韩菱纱.SaveGameData();
韩菱纱.Fight();
韩菱纱.DisplayData();
韩菱纱.RecoveryGameRole(c.Memento);
韩菱纱.DisplayData();
#endregion
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: