标签:
备忘录模式的作用就是存档。
比如你在玩一个可以存档的游戏。例如红警。你玩的很好,你想存起来下次接着玩。这个就是备忘录模式,代码如何实现呢?
使用代码:
BaseMemento BaseMemento1 = new BaseMemento(); LOL l1 = new LOL() { level = 1, Equipment = "红药水,罗兰之剑" }; BaseMemento1.Save("第一次", l1); LOL l2 = new LOL() { level = 6, Equipment = "电剑" }; BaseMemento1.Save("第二次", l2); LOL l3 = new LOL() { level = 10, Equipment = "电剑,鞋子s" }; BaseMemento1.Save("第三次", l3); BaseMemento1.Get("第一次").Show(); BaseMemento1.Get("第二次").Show(); BaseMemento1.Get("第三次").Show(); Console.ReadLine();
对象:
public class LOL { public int level { get; set; } public string Equipment { get; set; } public void Show() { Console.WriteLine("level={0},Equipment={1}", level, Equipment); } }
备忘录:
public class BaseMemento { public bool Save(string Name, LOL lol) { SerializeHelper.JsonSerializeHelper.Serialize<LOL, Stream>(lol, new FileStream(string.Format("{0}.txt", Name), FileMode.OpenOrCreate)); return true; } public LOL Get(string Name) { using (FileStream fsRead = new FileStream(string.Format("{0}.txt", Name), FileMode.Open)) { int fsLen = (int)fsRead.Length; byte[] heByte = new byte[fsLen]; int r = fsRead.Read(heByte, 0, heByte.Length); string myStr = System.Text.Encoding.UTF8.GetString(heByte); return SerializeHelper.JsonSerializeHelper.Deserialize<LOL>(myStr); } } }
结果:
标签:
原文地址:http://www.cnblogs.com/lystory/p/5684261.html