I've question about the philosophy of createMemento()
in Originator class in Memento Pattern.
My teacher said:
now that
Originator
class no longer storesMemento
objects internally, we should give it two new methods; createMemento() and setMemento().The
createMemento()
method stores the current state of the Originator inside a Memento 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 Memento object.
I'm confused. Because when I was trying to implement the Originator class that stores a list of Memento internally ,I still needed to have this createMemento()
method.
my class:
public class MyOriginator {
private String content;
//stores a list of Momento internally
private List<Momento> previousStates;
public MyOriginator() {
previousStates = new ArrayList<>();
}
public void push() {
previousStates.add(createMomento());
}
// need to have it.
private Momento createMomento() {
return new Momento(content);
}
public void pop() {
int lastIndex = previousStates.size() - 1;
this.content = previousStates.get(lastIndex).getContent();
previousStates.remove(lastIndex);
}
}
So createMemento()
seems to have nothing to do with storing or not storing Memento objects internally and storing or not storing Memento objects internally is not the reason of making and using of createMemento()
.
What is the reason for using and creating this method? in both case ( stores Memento objects internally and not storing Memento objects internally), I had to implement that method.
Aucun commentaire:
Enregistrer un commentaire