💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[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 ```