Java Behavioral Design Patterns – Memento Design Pattern

In this article, we will cover one Memento Design Pattern which is categorized under behavioral design patterns. This pattern provides the capability to provide a restore (like undo) functionality over an object.

The memento pattern operates on a single object. It will record the state of the object by protecting objects internal structure or by protecting encapsulation property. It is like an UNDO mechanism which will be useful to recover from errors. Memento pattern supports to save the object state information so one can restore it in any case of errors. You can opt for this design pattern if your application:

  • Needs to save the state of an object externally and you need to restore or rollback functionality
  • The objects follow strict encapsulations

Memento Design Pattern by Example

You need to provide 3 conceptual objects in order to successfully implement this pattern: Originator, Caretaker, and Memento

Originator

An originator is an object that has an internal state. It uses the memento to save and restore its internal state.

Caretaker

It never operates on the contents of a memento and it not even check the contents. It holds the memento object and is responsible for objects safekeeping. To restore the previous state, it returns the memento object to the originator.

Memento

A memento is an object that holds state information.

Let us go through a simple code. We will assume a simple game example. In this, if a user completes one round then it will be saved and he can start with next round. If a user fails to complete a round again they need to attempt previous round.

Memento Class

Originator

Caretaker

And here is the output:

Here we are simply mimicking that game is going on and states are saved automatically.

Conclusion

The Memento pattern is useful when there is a need to provide a Rollback mechanism in your program, so by using this pattern we can provide store and restore capability to an object.

You can refer complete code from our Git

Download Code

Add a Comment

Your email address will not be published. Required fields are marked *