如果我想确保在调用 setter 之后不能从外部修改对象,那么什么被认为是最佳和常见的做法?在代码中有详细的简单自我解释示例,有 2 个选项困境。
//caller scope
CustomObject original = new CustomObject(params...); //original state 1
MyClass mMyClass = new MyClass(original);
original.modifyMe(params...); //original state 2
mMyClass.setCustomObject(original);
original.modifyMe(params...); //original state 3
/*!!!REQUIREMENT: mMyClass.CustomObject should be in state 2!!!*/
class MyClass {
private CustomObject mObject;
public MyClass() {
this.mObject = new CustomObject();
}
public MyClass(CustomObject obj) {
this.mObject = obj.Clone();
}
//mObject is private, modified only through setter
public getCustomObject() {
return this.mObject;
}
public setCustomObject(CustomObject obj) {
//Option 1 in the caller
//mMyClass.setCustomObject(new CustomObject(params...));
this.mObject = obj;
//Option 2 in the caller
//mMyClass.setCustomObject(callerCustomObject);
this.mObject = obj.Clone();
}
}