Core Java

Java Memento Design Pattern Example

1. Introduction to Java Memento Design Pattern

In this article, we will discuss about one of the java design pattern – Java Memento Design Pattern. Memento design pattern is one of behavioural design patterns. Memento design pattern is mostly used when we like to save an object’s condition so that we can restore it later. Let us look deeply into what objects are. If we look at the real world, we can find many objects around us, vehicle, animals, people, etc. These objects have a state and a behaviour. If we take an example, consider a dog as object, then its state are name, breed, colour, and the behaviour are barking, wagging the tail, running. Memento design pattern is likely used to implement that in order to protect the integrity of the saved state data, saved state data of the object is not accessed outside the object.

In this article we will start with the explanation of various design patterns that are available, and followed by a real world example of the Memento design pattern. This might help to clarify exactly when you will use the java memento design pattern. After this, we will learn how to program the classes to implement a memento design pattern.

2. Types of Java Design Patterns

Design patterns are a popular concept in the development of software. A design pattern for a common software issue is a common and well described answer. A sensitive use of design patterns leads to greater coding maintenance, as design patterns can be recognised by others in addition to being a good solution to a common problem, thus reducing the curve in the handling of a specific piece of code. Design patterns consists of creational, structural and Behavioral design patterns.

2.1 Creational Pattern

Creational design patterns abstract the process of instantiation. This design pattern mainly depends upon two things are composition and inheritance. They allow us to make the pass from the hard coding of a fixed set of behaviours towards defining a smaller set of fundamental behaviours that can be composed into any number of more complex ones. This requires more than just the installation of a class for creating objects with specific behaviour. Five creational design patterns are there: Abstract Factory, Prototype, Factory Method, Builder, and Singleton.

2.2 Structural Pattern

Structural patterns relate to the arrangement of classes and objects to form larger structures. Inheritance in structural design patterns is used to compose interfaces or various implementations. For instance, a number of inheritance features of two or more classes can be combined into one class. This enables two or more class libraries to work together independently. This allows Structural object patterns specify how new objects can be created to create new features. The flexibility of the composition of the object enables us to modify the composition at run-times.

2.3 Behavioral Pattern

A Behavioral design pattern explains the interaction of objects. It describes how various objects and classes send data to each other so that things occur and how the particular task steps are divided into different objects. When creative patterns describe a time, and structural patterns describe a more or less static structure, Behavioral patterns describe a process or a flow.

Below in this article, we will discuss one of the behavioral design pattern – Memento design pattern. Memento design pattern is being used to preserve a preceding state of an object. You may want to save control points in your application and return to those control points later on, because your application is progressing.

3. Memento Design Pattern – Real life example

In this part, we will look into a real life example of the memento design pattern. The following example will elaborate how exactly memento design pattern is used to restore state of an object to a previous state. Here we consider an example of the changing the drum brakes of any vehicle to understand how it is identical to memento design pattern.

The following image shows the simple steps of how a mechanic or an individual changes the drum brake of any vehicle. The vehicle shown in the image are only for the understanding purpose and there is no direct relation with anyone.

Java Memento Design Pattern - Real World example
Memento Design Pattern Real World example

In the above image, it explains how the mechanics change or repair the drum brakes of a car and how it relates to memento design pattern. Initially the drums from the car are removed from the both sides, and then exposing both the right and left brakes of the car. After removing both the brakes only one side is disassembled and the other side act as a Memento of how the parts of the brake assembled together. Once the work has been completed on one side of the car then the other side will be disassembled. Whenever the other side is disassembled, the first side of the car acts as the Memento and vice versa.

We all know that memento design pattern is mainly used to restore the state of an object to a previous state.Hence, it is also known as snapshot pattern. A single object is operated by the memento design pattern.As it stores the state of the object through the protection of the internal structure of objects or by the protection of encapsulation. An another simple real life example of memento pattern is like a UNDO system in code editors, text editors such as word etc. that is very useful for error recovery. So, Memento design pattern is used to save information about the object state so that it can be restored by someone when error occurs.

4. Implementing Memento Design Pattern

In this section we will understand how memento design pattern works by implementing it in java program. Let us take an example of word document and restore its previous state with the help of memento design pattern.

In the following example, we will create memento for a word document object which has four basic attributes – id, title, heading and description. WordDocumentMemento class is used as memento for word document objects.

WordDocument.java

public class WordDocument
{
    private long id;
    private String title;
    private String heading;
    private String description;
     
    public WordDocument(long id, String title) {
        super();
        this.id = id;
        this.title = title;
    }
          
    public WordDocumentMemento createMemento()
    {
        WordDocumentMemento d = new WordDocumentMemento(id, title, heading, description);
        return d;
    }
     
    public void restore(WordDocumentMemento d) {
        this.id = d.getId();
        this.title = d.getTitle();
        this.heading = d.getHeading();
        this.description = d.getDescription();
    }
 
    @Override
    public String toString() {
        return "Word Document[id=" + id + ", title=" + title + ", heading="+ heading +", description=" + description + "]";
    }
}

In this above code, we have created a WordDocument class in which we have defined four variables id, title, heading, description. Also we have created WordDocument method with two parameters id and title in which super() method is called. Then we have created a memento for the WordDocument.

Then a restore() method for the word document is created with four attributes id, title, heading, description.

WordDocumentMemento.java

public final class WordDocumentMemento
{
    private final long id;
    private final String title;
    private final String heading;
    private final String description;
     
    public WordDocumentMemento(long id, String title, String heading, String description) {
        super();
        this.id = id;
        this.title = title;
        this.heading = heading;
        this.description = description;
    }
 
    public long getId() {
        return id;
    }
 
    public String getTitle() {
        return title;
    }

   public String getHeading() {
        return heading;
    }
 
    public String getDescription() {
        return description;
    }
}

We have created a final class WordDocumentMemento in which we have created four final variables id, title, heading and description. The function WordDocumentMemento with four parameters id, title, heading and description is used to get the values of the word document attributes. Then we created four methods getId(), getTitle(), getHeading(), getDescription() that returns the four attributes id, title, heading, description.

MementoDesignPattern.java

public class MementoDesignPattern
{
    public static void main(String[] args)
    {
        WordDocument document = new WordDocument(1, "My Article");
        document.setContent("ABC");    
        System.out.println(document);
         
        WordDocumentMemento memento = document.createMemento(); 
         
        document.setContent("XYZ");      
        System.out.println(document);
         
        document.restore(memento);       
        System.out.println(document);    
    }
}

The above class MementoDesignPattern includes main() Class in which we create a word document object document. Then we set content for the document and restore the content of the same document using setContent() and restore() methods.

Word Document[id=1, title=My Word Document, heading=Chapter 1, description=My First Word Document]
Word Document[id=1, title=My Word Document, heading=Chapter 1, description=My Second Word Document]
Word Document[id=1, title=My Word Document, heading=Chapter 1, description=My First Word Document]

In the output, initially we set the description of document as “My First Word Document” then on the second attempt we change the description to “My Second Word Document”. Then we restore the document description to the previous state.

5. Benefits of Memento Design Pattern

In this section we discuss several advantages of the memento design pattern. The following are the benefits of memento pattern listed:

  • Memento design pattern provides a way of storing the internal state of an object in a separate object without violating rule of design pattern.
  • Memento pattern records the objects state without understanding encapsulation.
  • It eliminates the requirement for multiple creation of the same object for the sole purpose of saving its state.
  • It mainly provides a recovery mechanism in case failure occurs.
  • This design pattern provides a way to maintain history of an object’s life cycle.
  • Help us when we want to restore back an abject to its previous state.
  • Help us when we want to maintain a history of states of an object.

6. Conclusion

Memento pattern is a formidable design pattern to store the condition of an object. Another usage is the ” Ok” and ” Cancel” dialogs, in which the object is stored when the dialog is loaded and the object is worked on. If you click’ Cancel,’ the user returns to the initial condition. In other words, the memento pattern is helpful where a roll- back mechanism is needed in your code, so we can record and restore an object by using this pattern.

7. Download the Project

You can download the project files for the above example from the below link:

Download
You can download the full source code of this example here: MemontoDesignPattern.zip

Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button