7

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.

barbara
  • 3,111
  • 6
  • 30
  • 58
  • Where's the `Caretaker` class here? – Luiggi Mendoza Aug 14 '14 at 17:51
  • I don't have it. Actually I don't understand why do I need it. – barbara Aug 14 '14 at 17:51
  • It may not look like a big difference with such a simple example, but it will help you later on to separate this construction code and model code. There's a good video about this: https://www.youtube.com/watch?v=RlfLCWKxHJ0 – Ozzy Aug 14 '14 at 18:09
  • 1
    Think about the Single Responsibility Principle as well as the Law of Demeter, as well as simplified testing and debugging. – Ozzy Aug 14 '14 at 18:15

1 Answers1

4

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.

jalynn2
  • 6,397
  • 2
  • 16
  • 15
  • 1
    But all this actions I can do with my instance directly. Like this `Memento memento = originator.save();` What's the point in `Caretaker`? To store collection of `Memento`s or for what? – barbara Aug 14 '14 at 18:03
  • Yes, to store the collections of `Memento`s. Creating `Memento`s is useless unless you keep them available to be restored later. That is the caretaker's job. – jalynn2 Aug 14 '14 at 18:09
  • Ok. In that case can I add logic for searching a certain Memento object in Caretaker? – barbara Aug 14 '14 at 18:23
  • Sure, you can do whatever you need to in there. Maybe you are creating them based on time, or the number of repetitions of some action, etc. The purpose of the caretaker to to encapsulate this logic so that it is in one place, and so that `Memento`s are not referenced throughout your application. – jalynn2 Aug 14 '14 at 18:28