Design Pattern (Part 06) — Memento Design Pattern

As we know there are two types of design patterns in java. Once the creational pattern and other, behavioral pattern. Memento is a part of the behavioral design pattern which is concerned with algorithms and the assignment of responsibilities between objects.

Definition

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

A memento design pattern describes as the when wants to save the state of an object so that can restore it later on (Promote undo or roll back to full object status). When used to store the data and restore to again use it. It can move to the back state without having any advanced implementations (Without violating encapsulation). There is the easiest example of this type is text editors, where we can save its data anytime and use undo to restore it to a previously saved state.

This pattern will be implemented by using a few main objects. Those are;

  1. Originator- It creates a memento containing a snapshot of its current internal state and uses the memento to restore its internal state. It’s one that initializes the memento with information that characterizes its current state. Moreover, it uses the memento to restore the internal state.
  2. Caretaker- This class is used for safekeeping memento’s snapshot of states.
  3. Memento- The memento object stores the internal state of the Originator.
Class Diagram

Real-world Example Scenario

Scenario concept Diagram

I want to buy 42 inches LED TV which is a 60000Rs and it won’t support a USB port. And I buy that LED TV and placed it in the hall. At some point in time, I thought let's buy a 46inch LED TV which is 80000Rs, and its supported USB port. So what I want to do is I want to place this 46inch TV in the hall. But already there is 42inch LED TV. So what I want to do is I want to put this 42 inch TV in the storeroom and place this 46inch LED TV in the hall. After some point of time thinking let me buy 50inch LED TV which cost 100,000Rs and it also supports a USB port. So I buy this 50inch LED TV and replace that in a hall. then I’ll put that 46inch LED TV in the storeroom. So now in the hall, 50inch LED TV is there. So after some point in time, I thought ok let me use 42inch LED TV. The clarity of the 50inch LED TV is not good. So basically I have to restore or rollback. So what I want to do is I have to put this 50inch LED TV in the storeroom and from the storeroom, I have to take the 42inch LED TV and place it into the hall. So basically what I’m doing is I’m rollback to the previous state.

Class Diagram For this Scenario

Let's see the implementation of this code. It will give a very clear understanding of this memento design pattern. In the below Github link, you can get the clear Implementation code.

Software Engineer at Virtusa (Pvt) Ltd.