Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 440
barbara Avatar asked Aug 14 '14 17:08

barbara


1 Answers

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.

like image 50
jalynn2 Avatar answered Oct 16 '22 10:10

jalynn2