Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »
Memento

Memento in Go

Memento is a behavioral design pattern that allows making 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.

Conceptual Example

The Memento pattern lets us save snapshots for an object’s state. You can use these snapshots to revert the object to the previous state. It’s handy when you need to implement undo-redo operations on an object.

originator.go: Originator

package main

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
}

memento.go: Memento

package main

type memento struct {
	state string
}

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

caretaker.go: Caretaker

package main

type caretaker struct {
	mementoArray []*memento
}

func (c *caretaker) addMemento(m *memento) {
	c.mementoArray = append(c.mementoArray, m)
}

func (c *caretaker) getMenento(index int) *memento {
	return c.mementoArray[index]
}

main.go: Client code

package main

import "fmt"

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.getMenento(1))
	fmt.Printf("Restored to State: %s\n", originator.getState())

	originator.restorememento(caretaker.getMenento(0))
	fmt.Printf("Restored to State: %s\n", originator.getState())

}

output.txt: Execution result

originator Current State: A
originator Current State: B
originator Current State: C
Restored to State: B
Restored to State: A

Memento in Other Languages

Design Patterns: Memento in Java Design Patterns: Memento in C# Design Patterns: Memento in C++ Design Patterns: Memento in PHP Design Patterns: Memento in Python Design Patterns: Memento in Ruby Design Patterns: Memento in Swift Design Patterns: Memento in TypeScript