Skip to main content

Command Palette

Search for a command to run...

Memento Design Pattern

Design Pattern Serie

Published
2 min read
Memento Design Pattern
M
A passionate software engineer who is interested in solving challenging problems, gaining new experiences, building exciting projects, and technical writing.

Intent

It lets us save and restore the previous state of an object without revealing the details of its implementation. So we can say that It encapsulates a checkpoint capability.

Problem

Imagine that we have a game and we want to save the progress (at which level we are) so that when we shut it down we can resume from where we left it,
but then we have 2 conditions as we want to save our progress (internal state) externally and at the same time encapsulation must not be violated (can't be accessed from an outside resource).

So what do you think should we do?

Solution

We must make an object (call it "originator") responsible for saving its internal state to a memento object and restoring to a previous state from a memento object.
Only the originator that created a memento is allowed to access it (consider it as a bridge). So we are now able to save and restore the internal state of the originator without violating its encapsulation.

Pros and Cons

Pros

  • It provides us with an easy way to maintain the history of the life cycle of an object.
  • We can produce snapshots of the object’s state without violating its encapsulation.

Cons

  • Dynamic programming languages such as Python don’t guarantee that the state within the memento stays untouched.
  • Lots of RAM may be consumed if clients create mementos too many times.

Thank you, and goodbye.

Design Patterns

Part 12 of 13

Different design patterns are explained in a simple fun way with examples based on the book "Head First Design Patterns" as a reference.

Up next

Proxy Design Pattern

Design Pattern Serie