Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
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
languagejava
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.

...

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.

...