备忘模式
代码实现:
实体类:
public class War3
{
public string Race { get; set; }
public string Hero { get; set; }
public string Army { get; set; }
public string Resource { get; set; }
public void Show()
{
Console.WriteLine($"种族: {Race},英雄:{Hero},军队:{Army},资源:{Resource}");
}
public void SaveCurrentProgress(string name)
{
MementoWar3 mementoWar3 = new MementoWar3(Hero,Army,Resource);
Caretaker.AddMementoWar3(name,mementoWar3);
}
public void LoadHistoryProgress(string name)
{
var mementoWar3 = Caretaker.GetMementoWar3(name);
this.Hero = mementoWar3.Hero;
this.Army = mementoWar3.Army;
this.Resource = mementoWar3.Resource;
}
}
备忘类+守护类:
public class MementoWar3
{
public string Hero { get; set; }
public string Army { get; set; }
public string Resource { get; set; }
public MementoWar3(string hero,string army,string resource)
{
Hero = hero;
Army = army;
Resource = resource;
}
}
public class Caretaker
{
private static readonly Dictionary<string,MementoWar3> DictMementoWar3 = new Dictionary<string, MementoWar3>();
public static void AddMementoWar3(string name, MementoWar3 mementoWar3)
{
DictMementoWar3.Add(name,mementoWar3);
}
public static MementoWar3 GetMementoWar3(string name)
{
return DictMementoWar3.ContainsKey(name) ? DictMementoWar3[name] : null;
}
}
代码调用:
class Program
{
static void Main(string[] args)
{
War3 war3 = new War3()
{
Race = "兽族",
Hero = "剑圣",
Army = "2个大G",
Resource = "200G 200W"
};
Console.WriteLine("开局...");
war3.Show();
war3.SaveCurrentProgress("Start");
Console.WriteLine("MF...");
war3.Hero = "剑圣 小Y";
war3.Army = "5个大G,3个狼骑,1个白牛";
war3.Resource = "500G 500W";
war3.Show();
war3.SaveCurrentProgress("MF");
Console.WriteLine("FinalFire...");
war3.Hero = "剑圣 小Y 老牛";
war3.Army = "5个大G,3个狼骑,1个白牛";
war3.Resource = "500G 500W";
war3.Show();
war3.SaveCurrentProgress("FinalFire");
Console.WriteLine("回到MF");
war3.LoadHistoryProgress("MF");
war3.Show();
Console.WriteLine("回到开局");
war3.LoadHistoryProgress("Start");
war3.Show();
}
}
结果:
