上一篇
在软件开发中,我们常常需要保存和恢复对象的某个状态。比如在文本编辑器中实现“撤销”功能,或者在游戏中保存玩家进度。这时候,C#备忘录模式就派上用场了!
本文将带你从零开始,深入浅出地理解C#设计模式中的备忘录模式(Memento Pattern),即使是编程小白也能轻松掌握。
备忘录模式是一种行为型设计模式,它允许在不破坏封装性的前提下,捕获并外部化一个对象的内部状态,以便以后可以将该对象恢复到原先保存的状态。
它主要包含三个角色:

使用备忘录模式示例可以帮助我们:
下面我们用一个简单的文本编辑器示例来演示如何在 C# 中实现备忘录模式。
public class TextMemento{ public string Content { get; private set; } public TextMemento(string content) { Content = content; }}public class TextEditor{ public string Content { get; set; } = ""; // 创建备忘录 public TextMemento CreateMemento() { return new TextMemento(Content); } // 恢复状态 public void RestoreFromMemento(TextMemento memento) { if (memento != null) { Content = memento.Content; } } public void Type(string text) { Content += text; } public override string ToString() { return $"当前内容: \"{Content}\""; }}public class History{ private Stack<TextMemento> _mementos = new Stack<TextMemento>(); public void Push(TextMemento memento) { _mementos.Push(memento); } public TextMemento Pop() { return _mementos.Count > 0 ? _mementos.Pop() : null; } public bool HasHistory => _mementos.Count > 0;}class Program{ static void Main(string[] args) { var editor = new TextEditor(); var history = new History(); // 输入内容 editor.Type("Hello"); Console.WriteLine(editor); // 保存状态 history.Push(editor.CreateMemento()); editor.Type(", World!"); Console.WriteLine(editor); // 再次保存 history.Push(editor.CreateMemento()); editor.Type(" How are you?"); Console.WriteLine(editor); // 撤销操作 if (history.HasHistory) { editor.RestoreFromMemento(history.Pop()); Console.WriteLine($"撤销后: {editor}"); } if (history.HasHistory) { editor.RestoreFromMemento(history.Pop()); Console.WriteLine($"再次撤销后: {editor}"); } }}程序输出如下:
当前内容: "Hello"当前内容: "Hello, World!"当前内容: "Hello, World! How are you?"撤销后: 当前内容: "Hello, World!"再次撤销后: 当前内容: "Hello"
通过这个简单的例子,你已经掌握了C#备忘录模式的核心思想和实现方式。这种设计模式教程不仅适用于文本编辑器,还可以广泛应用于需要状态保存与恢复的各种场景。
记住:备忘录模式的关键在于封装性——Caretaker 只负责保管 Memento,而不能访问或修改其内部数据,这保证了 Originator 的状态安全。
希望这篇关于C#设计模式的教程对你有帮助!动手试试吧,你会发现备忘录模式示例其实并不难理解。
本文由主机测评网于2025-12-12发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126762.html