Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and memento design is also one of the solution so we need to find the problem that Memento has solved and how ?
This design pattern comes under Behavioral Category (It tells that how objects are communicating with each other (objects have been created already)).
C++ Memento Design Pattern :
It defines that without violating encapsulation, it captures and externalise an object’s internal state so that the object can be restored to this state later.
In layman language:
Want to do undo or restore the previous state then just use memento.
We want roll back or restore previous state or promote undo like git tag(can roll back to previous commit).
Memento gives the restore property, we can use it to resolve above problems, this solution called as “memento design pattern“.
When we will use memento design pattern:
- When we need to save current state so that we can restore it later if required.
- When we have scenario in that we could need to jump to previous state.
- we can store previous state and we can restore it if required.
- It provide the encapsulation (memento is opaque to external world and only originator can access it)
- if storing object is large then its expensive operation.
- if storing object is large in number (frequently doing then its expensive operation).
- Client might be itself “care taker”.
- Originator only can read/write into memento.
- Care taker will contain memento but it will not able to peek into memento.
- Care taker will instruct originator to do the operations.
- Originator state is encapsulated and will be stored in memento based on instruction from care taker.
- Command can use memento to store the previous command.
Real Class Diagram Example:
Source code with real example: