12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- //备忘录是一种行为设计模式, 允许生成对象状态的快照并在以后将其还原。
- //
- //备忘录不会影响它所处理的对象的内部结构, 也不会影响快照中保存的数据。
- //
- //概念示例
- //备忘录模式让我们可以保存对象状态的快照。 你可使用这些快照来将对象恢复到之前的状态。 这在需要在对象上实现撤销-重做操作时非常实用。
- 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())
- }
|