ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 备忘录模式让我们可以保存对象状态的快照 ### 保存对象状态的快照 <details> <summary>main.go</summary> ``` package main import "fmt" // 原发器 type originator struct { state string } func (e *originator) createMemento() *memento { return &memento{state: e.state} } func (e *originator) restoreMemento(m *memento) { e.state = m.getSavedState() } func (e *originator) setState(state string) { e.state = state } func (e *originator) getState() string { return e.state } // 备忘录 type memento struct { state string } func (m *memento) getSavedState() string { return m.state } // 负责人 type caretaker struct { mementoArray []*memento } func (c *caretaker) addMemento(m *memento) { c.mementoArray = append(c.mementoArray, m) } func (c *caretaker) getMemento(index int) *memento { return c.mementoArray[index] } func main() { caretaker := &caretaker{ mementoArray: make([]*memento, 0), } originator := &originator{ state: "A", } fmt.Printf("Originator Current State: %s\n", originator.getState()) caretaker.addMemento(originator.createMemento()) originator.setState("B") fmt.Printf("Originator Current State: %s\n", originator.getState()) caretaker.addMemento(originator.createMemento()) originator.setState("C") fmt.Printf("Originator Current State: %s\n", originator.getState()) caretaker.addMemento(originator.createMemento()) originator.restoreMemento(caretaker.getMemento(1)) fmt.Printf("Restored to State: %s\n", originator.getState()) originator.restoreMemento(caretaker.getMemento(0)) fmt.Printf("Restored to State: %s\n", originator.getState()) } ``` </details> <br /> 输出 ``` Originator Current State: A Originator Current State: B Originator Current State: C Restored to State: B Restored to State: A ```