0
0
LldConceptBeginner · 3 min read

Memento Pattern: Definition, Example, and Use Cases

The Memento Pattern is a design pattern that lets you save and restore an object's state without exposing its internal details. It works like a snapshot, allowing you to undo or rollback changes safely.
⚙️

How It Works

Imagine you are writing a story and want to save drafts so you can go back to an earlier version if needed. The Memento Pattern works similarly by capturing an object's state at a point in time and storing it separately. This stored state is called a memento.

The main idea is to keep the object's internal details hidden while allowing its state to be saved and restored later. The object creates a memento containing its state, and an external caretaker keeps this memento safe. When needed, the caretaker gives the memento back to the object to restore its previous state.

💻

Example

This example shows a simple text editor that can save and restore its content using the Memento Pattern.

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

    def get_state(self) -> str:
        return self._state


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

    def type(self, words: str):
        self._content += words

    def save(self) -> Memento:
        return Memento(self._content)

    def restore(self, memento: Memento):
        self._content = memento.get_state()

    def get_content(self) -> str:
        return self._content


# Usage
editor = TextEditor()
editor.type("Hello, ")
editor.type("world!")
saved = editor.save()  # Save state

editor.type(" More text.")
print("Current content:", editor.get_content())

editor.restore(saved)  # Restore saved state
print("Restored content:", editor.get_content())
Output
Current content: Hello, world! More text. Restored content: Hello, world!
🎯

When to Use

Use the Memento Pattern when you need to save and restore an object's state without exposing its internal structure. It is especially useful for implementing undo/redo features in applications like text editors, graphic editors, or games.

It helps keep the code clean by separating the state-saving logic from the main object and protects the object's encapsulation by not exposing its internals.

Key Points

  • The pattern involves three roles: Originator (the object whose state is saved), Memento (the snapshot of state), and Caretaker (manages saved states).
  • It preserves encapsulation by not exposing the object's internal details.
  • Commonly used for undo/redo functionality.
  • Helps manage complex state changes safely.

Key Takeaways

Memento Pattern saves and restores object state without exposing internals.
It is ideal for undo/redo features in applications.
The pattern separates state storage from the main object.
It protects encapsulation while allowing rollback of changes.