Bird
0
0
LLDsystem_design~7 mins

Memento pattern in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When an object changes state frequently, it becomes difficult to restore it to a previous state without exposing its internal details. Without a controlled way to save and restore states, undo operations or rollback mechanisms can lead to errors or tight coupling between components.
Solution
The Memento pattern captures and externalizes an object's internal state without violating encapsulation, so the object can be restored to this state later. It uses a separate memento object to store the state, allowing the originator to save and restore its state safely.
Architecture
Client
Originator

This diagram shows the Client interacting with the Originator to save and restore state via the Memento object, which is managed by the Caretaker.

Trade-offs
✓ Pros
Preserves encapsulation by not exposing the internal state of the Originator.
Enables undo or rollback functionality by storing snapshots of state.
Separates state storage responsibility from the Originator, simplifying its design.
✗ Cons
Can increase memory usage if many states are saved as mementos.
Managing many mementos can add complexity to the Caretaker component.
Not suitable for very large or complex states without optimization.
Use when you need to implement undo/redo functionality or rollback state changes in an object without exposing its internals, especially when state changes are frequent but not continuous at very high scale.
Avoid when the object's state is very large or complex and saving/restoring state frequently would cause performance or memory issues.
Real World Examples
Microsoft Word
Uses the Memento pattern to implement undo and redo features by saving document states without exposing internal document structure.
Adobe Photoshop
Stores snapshots of image edits as mementos to allow users to revert to previous versions without exposing internal image data.
Eclipse IDE
Uses mementos to save and restore the state of UI components and editors during session persistence.
Code Example
Before applying the Memento pattern, the Editor exposes its internal state directly, risking tight coupling and breaking encapsulation. After applying the pattern, the Editor creates a Memento object to store its state, and the Caretaker manages these mementos. This keeps the Editor's state private and allows safe undo operations.
LLD
### Before (without Memento pattern):
class Editor:
    def __init__(self):
        self.content = ""

    def type(self, words):
        self.content += words

    def save(self):
        # No encapsulation, exposes internal state
        return self.content

    def restore(self, content):
        self.content = content


editor = Editor()
editor.type("Hello ")
saved = editor.save()
editor.type("World!")
print(editor.content)  # Hello World!
editor.restore(saved)
print(editor.content)  # Hello 


### After (with Memento pattern):

class Memento:
    def __init__(self, content):
        self._content = content

    def get_content(self):
        return self._content


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

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

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

    def restore(self, memento):
        self._content = memento.get_content()

    def get_content(self):
        return self._content


class Caretaker:
    def __init__(self):
        self._mementos = []

    def save_state(self, editor):
        self._mementos.append(editor.save())

    def undo(self, editor):
        if not self._mementos:
            return
        memento = self._mementos.pop()
        editor.restore(memento)


editor = Editor()
caretaker = Caretaker()

editor.type("Hello ")
caretaker.save_state(editor)

editor.type("World!")
print(editor.get_content())  # Hello World!

caretaker.undo(editor)
print(editor.get_content())  # Hello 
OutputSuccess
Alternatives
Command pattern
Stores operations as objects that can be executed or undone, rather than storing the entire state snapshot.
Use when: Use when you want to record user actions as commands for undo/redo rather than full state snapshots.
Snapshot pattern
Similar to Memento but often involves deep copying or serialization of the entire object state.
Use when: Use when you need a full copy of the object's state and can afford the overhead.
Summary
The Memento pattern helps save and restore an object's state without exposing its internals.
It enables undo and rollback functionality by storing snapshots in separate memento objects.
This pattern preserves encapsulation and separates state management from the main object.