Java Memento Pattern Tutorial 🎯

beginner
14 min

Java Memento Pattern Tutorial 🎯

Welcome to the Memento Pattern tutorial! In this lesson, we'll explore a design pattern that enables a program to save its internal state and revert to that state later. Let's dive in!

Understanding the Memento Pattern 📝

The Memento Pattern is a behavioral design pattern that allows an object to save its internal state and restore it later without violating encapsulation. It's useful in scenarios where we need to undo an action or revert an object to its previous state.

Key Components 📝

  1. Originator: The object that has a state we want to save and restore.
  2. Memento: A snapshot of the Originator's internal state.
  3. Caretaker: The object that keeps track of multiple Mementos.

Creating a Simple Memento Example 💡

Let's consider a real-world example: a text editor with undo functionality.

java
import java.util.Stack; public class TextEditor { private String content; private Stack<Memento> mementos = new Stack<>(); public TextEditor() { content = ""; } public void setContent(String content) { mementos.push(new Memento(this.content)); this.content = content; } public Memento getMemento() { return mementos.peek(); } public String getCurrentContent() { return content; } public static class Memento { private String content; public Memento(String content) { this.content = content; } public String getContent() { return content; } } }

In the example above, we have a TextEditor class that can store multiple versions of its content. Each time we call setContent(), the current content is saved in a Memento and added to the mementos stack.

Undo Functionality 💡

Now, let's add undo functionality to our TextEditor:

java
public void undo() { if (!mementos.isEmpty()) { content = mementos.pop().getContent(); } }

With this undo() method, we can revert the TextEditor's content to a previous state by popping the top Memento from the stack.

Memento Pattern Quiz 🎯

Quick Quiz
Question 1 of 1

What is the main purpose of the Memento Pattern?


In the next lesson, we'll explore another behavioral design pattern: the Command Pattern. Stay tuned! 😊