Why do we need a Caretaker class in the Memento Pattern? Is it really that important?

I'm currently trying to figure out how the Memento Pattern works. And did I stick to the Caretaker class? Is this really important? I mean, I can use Memento without this class. 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 implementation of Memento.

 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 great, and Memento works fine.

+6
source share
1 answer

The Caretaker is a class that calls the save() and restore() methods on the Originator . It keeps (takes on) the collection of Memento classes and decides when to breakpoint or roll back data.

+2
source

Source: https://habr.com/ru/post/973832/


All Articles