答案是通过命令模式封装请求,实现撤销操作。定义Command接口含Execute和Undo方法,具体命令如InsertCommand保存执行上下文并实现正反操作,CommandHistory用栈记录命令,支持多级撤销,每执行一命令入栈,撤销时弹出并调用其Undo方法,确保数据一致性,可扩展支持重做。
在Golang中实现命令模式来支持撤销操作,核心是将“请求”封装成独立的对象,使得可以参数化、记录、排队或撤销这些请求。命令模式通过解耦发送者与接收者,让撤销(Undo)和重做(Redo)变得灵活可控。
命令接口定义
定义一个统一的命令接口,包含执行和撤销两个方法:
每个具体命令都实现这个接口,确保调用方无需关心具体逻辑,只需调用统一方法。
具体命令示例:文本编辑操作
以一个简单的文本编辑器为例,实现“插入文本”命令及其撤销功能:
立即学习
“
go语言免费学习笔记(深入)
”;
Execute 添加文本,Undo 则移除最后添加的部分。注意要保存足够的上下文(如插入内容),以便反向操作。
go语言参考手册 中文CHM版
Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译
下载
命令管理器:支持多级撤销
使用一个历史栈记录已执行的命令,实现多级撤销:
每执行一个命令就压入历史栈,Undo 时弹出并调用其 Undo 方法。
使用方式示例
组合所有组件进行测试:
通过这种方式,可以轻松扩展更多命令(如删除、替换),并统一管理撤销流程。
基本上就这些。只要每个命令保存足够状态用于逆转操作,配合历史栈,就能实现稳定可靠的撤销机制。不复杂但容易忽略的是:确保 Undo 不会破坏数据一致性,必要时还需考虑重做(Redo)支持。
type Command interface {
Execute()
Undo()
}type TextEditor struct {
Content string
}
type InsertCommand struct {
editor *TextEditor
textToInsert string
}
func (c *InsertCommand) Execute() {
c.editor.Content += c.textToInsert
}
func (c *InsertCommand) Undo() {
if len(c.editor.Content) >= len(c.textToInsert) {
c.editor.Content = c.editor.Content[:len(c.editor.Content)-len(c.textToInsert)]
}
}type CommandHistory struct {
commands []Command
}
func (h *CommandHistory) Push(cmd Command) {
h.commands = append(h.commands, cmd)
}
func (h *CommandHistory) Undo() {
if len(h.commands) == 0 {
return
}
last := h.commands[len(h.commands)-1]
last.Undo()
h.commands = h.commands[:len(h.commands)-1]
}func main() {
editor := &TextEditor{}
history := &CommandHistory{}
cmd1 := &InsertCommand{editor, "Hello"}
cmd2 := &InsertCommand{editor, " World"}
cmd1.Execute()
history.Push(cmd1)
cmd2.Execute()
history.Push(cmd2)
fmt.Println("当前内容:", editor.Content) // 输出: Hello World
history.Undo()
fmt.Println("撤销一次后:", editor.Content) // 输出: Hello
history.Undo()
fmt.Println("再次撤销:", editor.Content) // 输出: ""
}