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

1

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.

Diao answered 14/8, 2014 at 17:48 Comment(4)
Where's the Caretaker class here?Orientation
I don't have it. Actually I don't understand why do I need it.Diao
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: youtube.com/watch?v=RlfLCWKxHJ0Winfordwinfred
Think about the Single Responsibility Principle as well as the Law of Demeter, as well as simplified testing and debugging.Winfordwinfred
M
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.

Millibar answered 14/8, 2014 at 17:57 Comment(4)
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 Mementos or for what?Diao
Yes, to store the collections of Mementos. Creating Mementos is useless unless you keep them available to be restored later. That is the caretaker's job.Millibar
Ok. In that case can I add logic for searching a certain Memento object in Caretaker?Diao
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 Mementos are not referenced throughout your application.Millibar

© 2022 - 2024 — McMap. All rights reserved.