go 示例
最后更新于:2022-04-02 04:21:07
[TOC]
## 示例
备忘录模式让我们可以保存对象状态的快照
### 保存对象状态的快照
输出 ``` Originator Current State: A Originator Current State: B Originator Current State: C Restored to State: B Restored to State: A ```
';
main.go
``` 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()) } ```输出 ``` Originator Current State: A Originator Current State: B Originator Current State: C Restored to State: B Restored to State: A ```