vendredi 3 juin 2016

Memento pattern drawbacks

So, here is an typical implementation of Memento pattern (skipped getters and setters).

public class Employee {
    private String name;
    private String phone;

    public EmployeeMemento save() {
        return new EmployeeMemento(name, phone);
    }

    public void revert(EmployeeMemento memento) {
        this.name = memento.getName();
        this.phone = memento.getPhone();
    }
}


  public class EmployeeMemento {
        private final String name;
        private final String phone;

        public EmployeeMemento(String name, String phone) {
            this.name = name;
            this.phone = phone;
        }
    }

public class Caretaker {
    private Stack<EmployeeMemento> history;

    public Caretaker() {
        history = new Stack<>();
    }

    public void save(Employee employee) {
        history.push(employee.save());
    }

    public void revert(Employee employee) {
        employee.revert(history.pop());
    }
}

All implementations of this pattern that I found are more or less equal to the one above. But there are some problems about this kind of implementation, that I don't like:

  1. It's possible to triger both employee.revert() and caretaker.revert(employee). I would like to have only one access point.
  2. If we want to change EmployeeMemento, we have to make changes in Employee class also (because of revert method).

Is there a way to overcome this? Or maybe I pay too much attention, and this details are not so important?

Aucun commentaire:

Enregistrer un commentaire