The Memento design pattern without violating encapsulation, captures and externalizes an object‘s internal state so that the object can be restored to this state later.
备忘录模式让程式能捕获外部的变化并改变内部的状态,有点像是游戏读取存档的功能~
学习目标: 备忘录模式的概念及实务
学习难度: ☆☆☆
using System;namespace ConsoleApp1{ public class Player { int money; public int Money { get { return money; } set { money = value; Console.WriteLine("Player's Money = " + money); } } public Memento CreateMemento() { return (new Memento(money)); } public void SetMemento(Memento memento) { Console.WriteLine("Return to last data..."); Money = memento.Money; } } public class Memento { int money; public Memento(int money) { this.money = money; } public int Money { get { return money; } } } public class Storage { Memento memento; public Memento Memento { set { memento = value; } get { return memento; } } } public class MainProgram { public static void Main(string[] args) { Player player = new Player(); player.Money = 100; Storage storage = new Storage(); storage.Memento = player.CreateMemento(); player.Money = 50; player.SetMemento(storage.Memento); } }}
参考资料:
https://www.dofactory.com/net/memento-design-pattern