如何制作在不可变对象中包含可变字段的可变对象的防御性副本?
class ImmutableObject {
private final MutableObject immutable_field;
ImmutableObject(MutableObject y) {
this.immutable_field = y;
}
}
class MutableObject {
public int mutable_field;
}
最佳答案
您需要做的是
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