What if you could rewind your app's state like a video, without messy code or bugs?
Why Memento pattern in LLD? - Purpose & Use Cases
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.
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 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.
saveState() { this.saved = JSON.stringify(this.data); }
restoreState() { this.data = JSON.parse(this.saved); }createMemento() { return new Memento(this.data); }
restore(memento) { this.data = memento.getState(); }It enables easy and safe state rollback, making features like undo, redo, and checkpoints possible without messy code.
Text editors use the Memento pattern to let you undo typing mistakes by restoring previous document states seamlessly.
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.
