What does "without violating encapsulation" mean in Memento pattern

lynxx :

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?

jaco0646 :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322664&siteId=1