Memento Design Pattern

sajjadali

Sajjad Ali

Posted on March 14, 2024

Memento Design Pattern

Introduction

As software engineers, we often find ourselves grappling with the challenge of managing an object’s state. Whether it’s undoing user actions, implementing version control, or creating snapshots, the Memento Pattern comes to our rescue. In this article, we’ll delve into the intricacies of this design pattern, explore its real-world applications, and understand how it can elevate your code to new heights.

What Is the Memento Pattern?

The Memento Pattern is like a time-travel machine for your objects. It allows you to capture an object’s internal state without exposing its nitty-gritty details. Imagine being able to save and restore an object’s past states effortlessly—like rolling back to a previous checkpoint in a video game.

How Does It Work?

The Players:Originator: Our main character—the object with an internal state.
Caretaker: The curious observer who wants to manipulate the originator but also needs an escape route. Memento: The magical capsule that holds the originator’s state.
The Plot Unfolds: The caretaker requests a memento from the originator (to save its internal state). The caretaker performs some operations on the originator. If things go awry, the caretaker hands back the memento to the originator (to restore the previous state).

Real-World Scenarios

  1. Undo/Redo Functionality

Imagine building a text editor. Users make changes, delete paragraphs, and insert emojis. With the Memento Pattern, you can save snapshots of the document’s state. When they hit “Undo,” voilà! The editor reverts to a previous version.

  1. Version Control

Git, anyone? The Memento Pattern aligns beautifully with versioning. Each commit is a memento—a snapshot of your codebase. Rollback to a specific commit, and you’re back in time, debugging like a pro.

  1. Custom Serialization

Ever needed to serialize an object in a specific way? Memento’s got your back. Save the internal state, transform it into a format of your choice, and restore it when needed.

Benefits of Using the Memento Pattern

Encapsulation Intact: The originator’s secrets remain hidden. No one messes with its private state.
Flexible Undo/Redo: Implementing undo/redo becomes a breeze.
Snapshot Magic: Capture moments in your application’s life cycle.

Implement Undo/Redo Features using Memento Design Pattern

UML Diagram for Memento Design Pattern

UML diagram for Memento Pattern Implementation

Code

import java.util.Stack;
public class EditorState {
    private final String content;
    private final String fontName;
    private final int fontSize;

    public String getContent() {
        return content;
    }

    public String getFontName() {
        return fontName;
    }

    public int getFontSize() {
        return fontSize;
    }

    public EditorState(String content, String fontName, int fontSize) {
        this.content = content;
        this.fontName = fontName;
        this.fontSize = fontSize;
    }

}

public class Editor {
    private String content;
    private String fontName;
    private int fontSize;

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFontName() {
        return fontName;
    }

    public void setFontName(String fontName) {
        this.fontName = fontName;
    }

    public EditorState createState() {
        return new EditorState(content, fontName, fontSize);
    }

    public void restore(EditorState state) {
        content = state.getContent();
    }
}

public class History {
    private Stack<EditorState> states = new Stack<>();

    public void push(EditorState state) {
        states.push(state);
    }

    public EditorState pop() {
        return states.pop();
    }

}

public class Main {

    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History();

        editor.setContent("a");
        history.push(editor.createState());

        editor.setContent("b");
        history.push(editor.createState());

        editor.setContent("c");
        editor.restore(history.pop());

        editor.restore(history.pop());

        System.out.println(editor.getContent());
    }

}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The Memento Pattern isn’t just a design pattern; it’s a time-traveling companion. So next time you need to save and restore states, channel your inner caretaker and embrace the magic of mementos.

Remember, every object has a story to tell—let the Memento Pattern be your ink and parchment.

💖 💪 🙅 🚩
sajjadali
Sajjad Ali

Posted on March 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Memento Design Pattern
memento Memento Design Pattern

March 14, 2024