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.