Appearance
Memento
Capture an object's internal state without violating encapsulation, and save this state externally so that it can be restored later.
The Memento pattern is primarily used to capture an object's internal state, allowing it to be restored at a later time.
In fact, almost all software we use employs the Memento pattern. The simplest form of the Memento pattern is saving to a file and opening a file. For a text editor, saving involves storing the string from the TextEditor
class to a file, and opening involves restoring the state of the TextEditor
class. For image editors, the principle is the same, but the format of the saved and restored data is more complex. Java's serialization can also be considered an implementation of the Memento pattern.
When using a text editor, we frequently use functionalities like Undo and Redo. These can also be implemented using the Memento pattern by periodically copying the string from the TextEditor
class and saving it, allowing us to Undo or Redo actions.
Roles in the Standard Memento Pattern
The standard Memento pattern involves the following roles:
- Memento: Stores the internal state.
- Originator: Creates a memento and sets its state.
- Caretaker: Responsible for saving the memento.
In practice, when using the Memento pattern, it doesn't need to be designed so intricately. For classes like TextEditor
, simply adding getState()
and setState()
methods suffices.
Example: TextEditor with Memento Pattern
Let's take a TextEditor
class as an example. It internally uses a StringBuilder
to allow users to add and delete characters:
java
public class TextEditor {
private StringBuilder buffer = new StringBuilder();
public void add(char ch) {
buffer.append(ch);
}
public void add(String s) {
buffer.append(s);
}
public void delete() {
if (buffer.length() > 0) {
buffer.deleteCharAt(buffer.length() - 1);
}
}
}
To support saving and restoring the state of TextEditor
, we add getState()
and setState()
methods:
java
public class TextEditor {
...
// Get the current state:
public String getState() {
return buffer.toString();
}
// Restore to a previous state:
public void setState(String state) {
this.buffer.delete(0, this.buffer.length());
this.buffer.append(state);
}
}
For this simple text editor, a String
can represent its state. For more complex object models, formats like JSON or XML are typically used.
Exercise
Add the Memento pattern to the TextEditor
.
Summary
The Memento pattern is designed to save an object's internal state and restore it later. Most software features that offer saving and opening files, as well as Undo and Redo operations during editing processes, are applications of the Memento pattern.