Hello Guys. I’ve question about the philosophy of createState() in Originator class in Memento Pattern.
Mosh said:
now that Editor(Originator) class no longer stores EditorState(Memento) objects internally, we should give it two new methods; createState() and restoreState().
The createState() method stores the current state of the Editor inside a State object and returns it. So we call this method and say, “Hey, save your current state and give it to me”, we’ll get an EditorState object.
I’m confused. Because when I was trying to implement the Originator (Editor) class that stores a list of EditorState internally ,I still needed to have this createState() method.
my class:
public class MyEditor2 {
private String content;
private String title;
//stores a list of EditorState internally
private List<EditorState> previousStates;
public MyEditor2() {
previousStates = new ArrayList<>();
}
public void push() {
previousStates.add(createState());
}
// need to have it.
private EditorState createState() {
return new EditorState(content, title);
}
public void pop() {
int lastIndex = previousStates.size() - 1;
this.content = previousStates.get(lastIndex).getContent();
this.title = previousStates.get(lastIndex).getTitle();
previousStates.remove(lastIndex);
}
public void setContent(String content) {
this.content = content;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
What is the reason for using and creating this method? in both case ( stores EditorState(Memento) objects internally and not storing EditorState(Memento) objects internally), I had to implement that method.