What does "without violating encapsulation" mean in Memento pattern

441 Views Asked by At

Wikipedia's description of the Memento pattern states that:

  • The internal state of an object should be saved externally so that the object can be restored to this state later.

  • The object's encapsulation must not be violated.

I'm confused as to how can encapsulation be violated? Is it referring to the getter methods of the fields stored in memento?

2

There are 2 best solutions below

0
jaco0646 On BEST ANSWER

I'm confused as to how can encapsulation be violated? Is it referring to the getter methods of the fields stored in memento?

Yes, it is referring to getter methods of the fields to be stored in the Memento. The object which has these fields (aka the Originator) does not want to violate its own encapsulation by exposing its fields publicly. The problem then is how to save the fields (into a Memento) without making them public.

In other words, how can we save private fields without adding getter methods? We don't want to violate encapsulation by exposing the data inside our (Originator) object in any way.

Refactoring Guru has an excellent article explaining this.

0
Ori Marko On

I think that it refers to Memento object encapsulation, which is used to restore state and accessible from Originator only

If you notice in implementation Memento object doesn't have setter, its inner state is only updated on constructor/creation

public static class Memento {
    private final String state;    
    public Memento(String stateToSave) {
        state = stateToSave;
    }       
    // accessible by outer class only
    private String getSavedState() {
        return state;
    }
}