Autumn SALE
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) getMemento(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.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())

}

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

Memento in C# Memento in C++ Memento in Java Memento in PHP Memento in Python Memento in Ruby Memento in Rust Memento in Swift Memento in TypeScript