...
Code Block | ||
---|---|---|
| ||
package MementoPattern; //This is our Memento public class EditorState { private final String content; public EditorState(String content) { this.content = content; } public String getContent() { return content; } } |
The EditorState
class serves as the Memento and is responsible for storing the state of an editor. Let's break down the code:
...
Code Block | ||
---|---|---|
| ||
package MementoPattern; //This is out Originator public class Editor { private String content; public EditorState createState() { return new EditorState(content); } public void restore(EditorState state) { content = state.getContent(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } |
The provided code represents an Originator class in the context of the Memento design pattern.
...
The purpose of this Editor
class is to serve as the Originator, which is responsible for creating Memento objects (EditorState
) that capture the state of the editor, as well as restoring the state of the editor from a given Memento. It encapsulates the state within the content
attribute and provides methods to create and restore Memento objects.
Code Block | ||
---|---|---|
| ||
package MementoPattern; import java.util.ArrayList; import java.util.List; //This is out Caretaker public class History { //We could actually use a stack here - but I have chosen to use a LIST private List<EditorState> states = new ArrayList<>(); public void push(EditorState state) { states.add(state); } public EditorState pop() { var lastIndex = states.size() - 1; var lastState = states.get(lastIndex); states.remove(lastState); return lastState; } } |
The provided code represents a Caretaker class in the context of the Memento design pattern.
...