Memento模式通过封装对象状态实现撤销功能,文中以Go语言文本编辑器为例,展示Originator(编辑器)、Memento(状态快照)和Caretaker(历史管理)的协作,支持安全的状态回滚与恢复。

在Go语言开发中,当需要保存和恢复对象的内部状态时,Memento(备忘录)模式是一种优雅的解决方案。它可以在不破坏封装性的前提下,实现状态的快照与回滚。本文通过一个简单的文本编辑器示例,展示如何在Golang中实践Memento模式。
Memento模式用于捕获并外部化一个对象的内部状态,以便之后可以将该对象恢复到原先的状态。它通常包含三个角色:
假设我们有一个简单的文本编辑器,支持输入文本和撤销操作。我们可以使用Memento模式来保存每次修改前的状态。
// 文本编辑器(Originator)
type Editor struct {
text string
}
立即学习“go语言免费学习笔记(深入)”;
func (e *Editor) SetText(text string) {
e.text = text
}
func (e *Editor) GetText() string {
return e.text
}
func (e Editor) CreateMemento() Memento {
return &Memento{text: e.text}
}
func (e Editor) Restore(m Memento) {
e.text = m.text
}
// 备忘录结构体(Memento)
type Memento struct {
text string
}
// 状态管理器(Caretaker)
type History struct {
mementos []*Memento
}
func (h History) Save(editor Editor) {
m := editor.CreateMemento()
h.mementos = append(h.mementos, m)
}
func (h History) Undo(editor Editor) {
if len(h.mementos) == 0 {
return
}
lastIndex := len(h.mementos) - 1
m := h.mementos[lastIndex]
editor.Restore(m)
h.mementos = h.mementos[:lastIndex]
}
下面是一个调用流程,演示如何利用备忘录进行撤销操作:
func main() {
editor := &Editor{}
history := &History{}
editor.SetText("第一版内容")
history.Save(editor)
editor.SetText("第二版内容")
history.Save(editor)
editor.SetText("第三版内容")
fmt.Println("当前内容:", editor.GetText()) // 输出:第三版内容
history.Undo(editor)
fmt.Println("撤销一次后:", editor.GetText()) // 输出:第二版内容
history.Undo(editor)
fmt.Println("再撤销一次:", editor.GetText()) // 输出:第一版内容
}
Memento模式的关键在于保持封装性。Originator可以访问Memento的全部内容,而Caretaker只能持有和传递Memento,不能读取其内部状态。
基本上就这些。Memento模式在实现撤销/重做、事务回滚、快照等功能时非常实用,结合Go的结构体与指针机制,实现简洁且高效。
以上就是Golang Memento备忘录模式状态保存实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号