1、发起者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento
{
/// <summary>
/// 角色 (发起者 备忘对象)
/// </summary>
public class RoleOriginatory
{
/// <summary>
/// 生命力 100
/// </summary>
public int Hp { get; set; }
/// <summary>
/// 攻击力
/// </summary>
public int Attack { get; set; }
public RoleOriginatory()
{
Hp = 100;
Attack = 50;
}
public override string ToString()
{
string strShow = "--- 生命力:" + Hp.ToString() + "\n 攻击力:" + Attack.ToString();
return strShow;
}
/// <summary>
/// 攻击
/// </summary>
public void Fight()
{
this.Attack += 2;
this.Hp -= 10;
}
/// <summary>
/// 保存快照
/// </summary>
/// <returns></returns>
public RoleMemento SaveState()
{
return new RoleMemento(this.Hp, this.Attack);
}
/// <summary>
/// 恢复快照
/// </summary>
public void RecoveryState(RoleMemento memento)
{
this.Hp = memento.Hp;
this.Attack = memento.Attack;
}
}
}
2、备忘录
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento
{
/// <summary>
/// 角色的备忘录
/// </summary>
public class RoleMemento
{
/// <summary>
/// 生命力 100
/// </summary>
public int Hp { get; set; }
/// <summary>
/// 攻击力
/// </summary>
public int Attack { get; set; }
public RoleMemento(int hp, int attack)
{
this.Hp = hp;
this.Attack = attack;
}
}
}
3、备忘录管理者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento
{
/// <summary>
/// 角色管理者
/// </summary>
public class RoleCaretaker
{
private RoleMemento memento;
public RoleMemento GetRoleMemento()
{
return this.memento;
}
public void SetRoleMemento( RoleMemento memento)
{
this.memento = memento;
}
}
}
4、使用备忘录
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("备忘录设计模式");
// 创建发起者
RoleOriginatory role = new RoleOriginatory();
Console.WriteLine(role.ToString());
// 攻击
role.Fight();
Console.WriteLine("攻击-----------------");
Console.WriteLine(role.ToString());
// 当前状态 存档
Console.WriteLine("存档-----------------");
RoleCaretaker roleCaretaker = new RoleCaretaker();
roleCaretaker.SetRoleMemento(role.SaveState());
// 存档后攻击
role.Fight();
role.Fight();
role.Fight();
role.Fight();
Console.WriteLine("多次攻击-----------------");
Console.WriteLine(role.ToString());
// 恢复快照
Console.WriteLine("恢复快照-----------------");
role.RecoveryState(roleCaretaker.GetRoleMemento());
Console.WriteLine(role.ToString());
Console.ReadLine();
}
}
}
优缺点
优点
- 提供了状态的保存机制
- 实现了信息的封装,只需要调用存档与恢复即可
缺点
- 消耗更多的资源