diff --git a/README.md b/README.md index a2aa116..2f5ea86 100644 --- a/README.md +++ b/README.md @@ -98,5 +98,8 @@ Define an object that encapsulates how a set of objects interact.Mediator promot ### Template Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure. +### Memento +Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. + ## Concurrency patterns Pattenrs for concurrent work and parallel execution in Go. diff --git a/behavioral/memento/memento.go b/behavioral/memento/memento.go new file mode 100644 index 0000000..743ecc0 --- /dev/null +++ b/behavioral/memento/memento.go @@ -0,0 +1,39 @@ +package memento + +import ( + "errors" +) + +type State struct { + Description string +} + +type memento struct { + state State +} + +type originator struct { + state State +} +func (o *originator) StoreStateToMemento() memento { + return memento{state: o.state} +} +func (o *originator) StoreStateFromMemento(m memento) { + o.state = m.state +} + +type careTaker struct { + mementos []memento +} +func (c *careTaker) Push(m memento) { + c.mementos = append(c.mementos, m) + +} +func (c *careTaker) Get(i int) (memento, error) { + var m memento + if len(c.mementos) < i || i< 0 { + return m, errors.New("Index is out of range") + } + + return c.mementos[i], nil +} \ No newline at end of file