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!
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.
Let's consider a real-world example: a text editor with undo functionality.
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.
Now, let's add undo functionality to our TextEditor:
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.
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! 😊