如何制作在不可变对象中包含可变字段的可变对象的防御性副本?

class ImmutableObject {

  private final MutableObject immutable_field;

  ImmutableObject(MutableObject y) {
    this.immutable_field = y;
  }
}

class MutableObject {

  public int mutable_field;
}
  • MutableObject没有让我设置字段的构造函数。
  • MutableObject的当前状态应该在Immutable Object中捕获,并且永远不要更改。
  • 最佳答案

    您需要做的是

      MutableObject return_immutable_field() {
        return immutable_field;
      }
    

    改成:
      MutableObject return_immutable_field() {
        MutableObject tmp = new MutableObject();
        tmp.mutable_field = immutable_field.mutable_field;
        return tmp;
      }
    

    有关说明,请参见http://www.javapractices.com/topic/TopicAction.do?Id=15

    09-10 17:14