Why we need Caretaker class in Memento Pattern? Is it really so important?

1.8k Views Asked by At

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.

1

There are 1 best solutions below

4
On BEST ANSWER

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.