unj*_*nj2 3 java defensive-copy effective-java
如何制作包含不可变对象中可变字段的可变对象的防御性副本?
class ImmutableObject {
private final MutableObject immutable_field;
ImmutableObject(MutableObject y) {
this.immutable_field = y;
}
}
class MutableObject {
public int mutable_field;
}
Run Code Online (Sandbox Code Playgroud)
你需要做的是在
MutableObject return_immutable_field() {
return immutable_field;
}
Run Code Online (Sandbox Code Playgroud)
改成:
MutableObject return_immutable_field() {
MutableObject tmp = new MutableObject();
tmp.mutable_field = immutable_field.mutable_field;
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
有关说明,请参阅http://www.javapractices.com/topic/TopicAction.do?Id=15