What is the memo mode
Memo pattern is a behavior design pattern that allows you to save and restore the previous state of an object without exposing the implementation details of the object.
Why use memo mode
When you need to create a snapshot of the state of an object to restore its previous state, you can use memo mode. Alternatively, you can use this pattern when direct access to the object’s member variables, getters, or setters will cause the encapsulation to break through.
How to implement memo mode
memento. Go memo
Memos are used to maintain the state of objects.
package memento
type memento struct {
state string
}
func (m *memento) getSavedState() string {
return m.state
}
originator. Go initiator
The originator is the base object. It will keep its status until the memo.
package memento
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
}
caretaker. Go Manager
Objects that hold multiple memos and maintain their indexes for retrieval.
package memento
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]
}
example. Go client call example
package memento
import "fmt"
func Example() {
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())
}
advantage
- You can create object state snapshots without destroying object encapsulation.
- You can simplify the originator code by having the owner maintain the originator status history.
shortcoming
- If the client creates memos too often, the program will consume a lot of memory.