Bird
0
0
LLDsystem_design~3 mins

Why Memento pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could rewind your app's state like a video, without messy code or bugs?

The Scenario

Imagine you are writing a drawing app where users can undo and redo their actions. Without a system to save states, you try to manually track every change by copying the entire drawing each time. This quickly becomes confusing and slow.

The Problem

Manually saving every change means lots of repeated code and high memory use. It's easy to forget to save a state or restore it incorrectly, causing bugs. Undo and redo become unreliable and hard to maintain.

The Solution

The Memento pattern lets you save an object's state safely without exposing its details. You can store snapshots and restore them later, making undo/redo simple, clean, and reliable.

Before vs After
Before
saveState() { this.saved = JSON.stringify(this.data); }
restoreState() { this.data = JSON.parse(this.saved); }
After
createMemento() { return new Memento(this.data); }
restore(memento) { this.data = memento.getState(); }
What It Enables

It enables easy and safe state rollback, making features like undo, redo, and checkpoints possible without messy code.

Real Life Example

Text editors use the Memento pattern to let you undo typing mistakes by restoring previous document states seamlessly.

Key Takeaways

Manually tracking state changes is error-prone and inefficient.

Memento pattern cleanly separates state saving and restoring.

It simplifies undo/redo and improves code maintainability.