"without violating encapsulation" 在 Memento 模式中意味着什么

What does "without violating encapsulation" mean in Memento pattern

维基百科对 Memento pattern 的描述指出:

  • 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.

我对如何违反封装感到困惑?是指memento中存储的字段的getter方法吗?

我认为是指Memento对象封装,用于恢复状态,只能从Originator访问

如果您在实施中注意到 Memento 对象没有 setter,其内部状态仅在 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;
    }
}

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

是的,指的是getter Memento中存储字段的方法。具有这些字段的对象(又名发起者)不想通过暴露其字段 publicly 来违反其自身的封装。那么问题是如何在不使字段 public.

的情况下保存字段(到 Memento 中)

也就是说,不加getter方法,如何保存私有字段呢?我们不想通过以任何方式公开我们的 (Originator) 对象中的数据来违反封装。

Refactoring Guru 有一篇很好的文章对此进行了解释。