The Memento Design Pattern in Python

Fhuseynov
2 min readOct 10, 2023

--

The Memento design pattern is a behavioral pattern in software design that allows you to capture and externalize an object’s internal state so that it can be restored to that state later. This pattern is useful when you need to implement features like undo/redo functionality, checkpoint systems, or any situation where you want to save and restore an object’s state.

The Memento Design Pattern

The Memento pattern involves three main components:

  1. Originator: This is the object whose state we want to save and restore. It creates a Memento object to store its state.
  2. Memento: This is an immutable object that stores the state of the Originator. It has two main methods: getState() to retrieve the saved state and setState() to set the state.
  3. Caretaker: This is responsible for keeping track of the Mementos and can request the Originator to restore its state from a Memento.

Example in Python

Let’s implement the Memento design pattern with a simple Python example. Imagine we have a text editor with undo and redo functionality.

class Memento:
def __init__(self, state):
self._state = state

def get_state(self):
return self._state


class TextEditor:
def __init__(self):
self._text = ""

def write(self, text):
self._text += text

def get_text(self):
return self._text

def create_memento(self):
return Memento(self._text)

def restore(self, memento):
self._text = memento.get_state()


class History:
def __init__(self):
self._history = []

def push(self, memento):
self._history.append(memento)

def pop(self):
if self._history:
return self._history.pop()


# Usage
editor = TextEditor()
history = History()

editor.write("Hello, ")
history.push(editor.create_memento())

editor.write("world!")
history.push(editor.create_memento())

print("Current Text:", editor.get_text())

editor.restore(history.pop())
print("Undo:", editor.get_text())

editor.restore(history.pop())
print("Undo:", editor.get_text())

In this example, we have a TextEditor class that allows us to write text and create mementos to save its state. The History class keeps track of these mementos, allowing us to undo our changes.

Conclusion

The Memento design pattern is a powerful tool for managing and restoring an object’s state. It can be applied in various scenarios beyond text editors, such as games, database transactions, or any application where you need to keep a history of states and support undo/redo operations. Understanding and implementing this pattern in Python can greatly improve the maintainability and functionality of your software.

--

--