Memento Design Pattern in Java: Preserving Object States

In this article, we will do an in-depth exploration of Memento Design Pattern in Java. So, let’s get started.

What is Memento Design pattern in Java?

The Memento Design Pattern in Java provides a way to capture and restore the internal state of an object without violating encapsulation. This article explores the benefits of using Memento Design Pattern, its implementation in Java, and its real-world use cases.

Benefits of using Memento Design pattern in Java

The Memento Design Pattern in Java offers several benefits in software development:

  1. State preservation: The pattern allows for the preservation of an object’s internal state, providing the ability to restore it to a previous state when needed. This is useful in scenarios where you need to undo actions or revert back to a specific point in time.
  2. Encapsulation of state: The Memento pattern encapsulates the state of an object within a separate Memento object. This promotes encapsulation and information hiding, as the object’s internal state is not exposed directly to other objects.
  3. Separation of concerns: The pattern separates the responsibility of state management from the main object, improving code organization and making it easier to maintain and extend.
  4. Snapshot capabilities: The Memento pattern provides a snapshot of an object’s state at a specific moment, allowing you to capture and store different versions of an object’s state for analysis or comparison purposes.
  5. Improved system reliability: By capturing and restoring object states, the Memento pattern can contribute to the overall reliability of a system. It helps prevent data loss and allows for safe recovery in case of errors or failures.

Use-Cases: Memento Design pattern in Java

The Memento Design Pattern has several real-world use cases in Java applications. Some of them include:

  1. Checkpointing and recovery: In systems where the state of an object needs to be periodically saved and restored, the Memento pattern can be used. This is common in applications like document editors, where automatic saving or recovery of unsaved changes is necessary.
  2. Caching: The Memento pattern can be applied in caching mechanisms. By storing the state of an object in a memento, you can avoid the need to fetch data from a data source repeatedly. This can improve performance in situations where the same data is accessed frequently.
  3. Game state management: In game development, the Memento pattern can be used to manage the state of a game. It allows saving and restoring game progress, enabling features like saving game sessions, checkpoints, or allowing players to resume from a specific point.
  4. Configuration management: The Memento pattern can be employed in systems that require configuration management. It allows saving and restoring different configurations of an application, making it easy to switch between settings or revert to a known working configuration.
  5. Database transactions: The Memento pattern can be utilized in database transactions. It enables saving the state of the database before making changes and provides the ability to rollback the changes if needed, ensuring data integrity and consistency.

Components of Memento Design pattern in Java

Memento Design pattern in Java
  • originator – the object for which the state is to be saved. It creates the memento and uses it in future to undo.
  • memento – the object that is going to maintain the state of originator.
  • caretaker – the object that keeps track of multiple memento. Like maintaining savepoints.

Code Example: Memento Design pattern in Java

Java Code

// Originator Class

package com.design.memento;

public class Originator {

    private String state;

    public Originator(String state) {
        this.state = state;
    }

    public Memento saveToMemento() {
        System.out.println("Originator: Saving to Memento.");
        return new Memento(this.state);
    }

    public void restoreFromMemento(Memento memento) {
        this.state = memento.getState();
        System.out.println("Originator: State after restoring from Memento: " + state);
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

// Memento class

package com.design.memento;

public class Memento {

    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

// CareTaker Class

package com.design.memento;

import java.util.ArrayList;
import java.util.List;

public class CareTaker {

    private List states = new ArrayList < > ();

    public void addMemento(Memento m) {
        states.add(m);
    }

    public Memento getMemento(int index) {
        return states.get(index);
    }

}

// MementoDemo Class

package com.design.memento;

public class MementoDemo {

    public static void main(String[] args) {
        Originator originator = new Originator("State #1");
        CareTaker caretaker = new CareTaker();
        caretaker.addMemento(originator.saveToMemento());
        originator.setState("State #2");
        originator.setState("State #3");
        caretaker.addMemento(originator.saveToMemento());
        System.out.println("Originator Current State: " + originator.getState());
        System.out.println("Originator restoring to previously saved state...");
        originator.restoreFromMemento(caretaker.getMemento(0));
        System.out.println("Originator Current State: " + originator.getState());
    }

}

// Output
Originator: Saving to Memento.
Originator: Saving to Memento.
Originator Current State: State #3
Originator restoring to previously saved state...
Originator: State after restoring from Memento: State # 1
Originator Current State: State #1

Conclusion: Memento Design pattern in Java

In this article, we delved into the intricacies of the Memento Design Pattern in Java, a valuable tool for capturing and restoring an object’s internal state while maintaining encapsulation. By discussing its benefits, practical implementation, and real-world applications, you’ve gained insights into how this pattern enhances code flexibility, separation of concerns, and reliability. The provided code example illustrates the Memento pattern in action, showcasing its utility in managing object states effectively. With a solid understanding of the Memento pattern, you’re better equipped to create more robust and adaptable Java applications.

Must Read Design Pattern Articles: 

For more comprehensive understanding you can go through the book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, also known as the “Gang of Four” (GoF) Design Patterns: Elements of Reusable Object-Oriented Software

Leave a Reply

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