I currently trying to figure out how Memento Pattern works. And I stuck with Caretaker
class? Is it really important to have it? I mean I can use Memento without this class. Please see my code below.
public class Originator {
private String state;
private Integer code;
private Map<String, String> parameters;
// Getters, setters and toString were omitted
public Memento save() {
return new Memento(this);
}
public void restore(Memento memento) {
this.state = memento.getState();
this.code = memento.getCode();
this.parameters = memento.getParameters();
}
}
Here is the Memento implementation.
public class Memento {
private String state;
private Integer code;
private Map<String, String> parameters;
public Memento(Originator originator) {
Cloner cloner = new Cloner();
this.state = cloner.deepClone(originator.getState());
this.code = cloner.deepClone(originator.getCode());
this.parameters = cloner.deepClone(originator.getParameters());
}
// Getters and setters were omitted
}
This code works fine and Memento does its work perfect.
The Caretaker is the class that calls the save()
and restore()
methods on Originator
. It holds onto (Takes care of) the collection of Memento
classes and decides when to checkpoint or roll back the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With