备忘录模式(Memento Pattern)又叫做快照模式(Snapshot Pattern)或Token模式,是GoF的23种设计模式之一,属于行为模式。
定义(源于GoF《设计模式》):在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
个人理解
在一个类(发起人)中,需要定义一个变量来存储这个类的某些属性在发生变化前的值,因此可以在Originato中定义一个Memento变量,而省去Caretaker这个类
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MemoDemo
{
class Program
{
static void Main(string[] args)
{
GameRole role = new GameRole(100,10000,1000);
role.Show();
role.Store();
role.Fight();
role.Show();
role.Reset();
role.Show();
}
}
public class GameRole
{
public int HP;
public int Attack;
public int Defense;
public Memo memo;
public GameRole(int _hp, int _attack, int _def)
{
this.HP = _hp;
this.Attack = _attack;
this.Defense = _def;
}
public void Fight()
{
Console.WriteLine("战斗结束");
this.HP = 0;
this.Attack = 0;
this.Defense = 0;
}
public void Show()
{
Console.WriteLine("显示当前状态");
Console.WriteLine("当前血量{0}", this.HP);
Console.WriteLine("当前攻击力{0}", this.Attack);
Console.WriteLine("当前防御力{0}", this.Defense);
Console.WriteLine();
}
public void Store()
{
this.memo = new Memo(this.HP, this.Attack, this.Defense);
}
public void Reset()
{
if(this.memo == null)
{
return;
}
Console.WriteLine("状态重置");
this.HP = this.memo.HP;
this.Attack = this.memo.Attack;
this.Defense = this.memo.Defense;
}
}
public class Memo
{
public int HP;
public int Attack;
public int Defense;
public Memo(int _hp, int _attack, int _def)
{
this.HP = _hp;
this.Attack = _attack;
this.Defense = _def;
}
}
}