All Articles

Behavioral Design Pattern: Memento

This article was done using my notes from:

Alexander Shvets (2019), Dive into Design Patterns, Refactoring.Guru

Memento

Memento pattern allows to make snapshots of an object’s state and restoring it in future. The Memento doesn’t compromise the internal structure of the object it works with, as well as data kept inside the snapshots.

Structure

Memento

Code

package main

import "fmt"

type Memento struct {
	state string
}

func (m *Memento) getSavedState() string {
	return m.state
}

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 Caretaker struct {
	mementos []*Memento
}

func (c *Caretaker) addMemento(m *Memento) {
	c.mementos = append(c.mementos, m)
}

func (c *Caretaker) getMemento(index int) *Memento {
	return c.mementos[index]
}

func main() {
	caretaker := &Caretaker{
		mementos: 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())
}