[英]How to maintain Immutable nature of a class referencing Mutable Objects?
I am well aware of rules to make a class Immutable. 我很清楚使类不可变的规则。 But Consider a situation where my class A which compose class B. Class B is in external jar and Class B again compose of C and D ie 但是考虑一下这样的情况:我的A类组成B类。B类在外部jar中,而B类再次组成C和D,即
class A{
B b;
}
// External library
class B{
C c;
D d;
}
class C{
}
class D{
}
How can I make class A Immutable if I can't modify classes in External lib? 如果无法在外部库中修改类,如何使A类不可变? If classes in External lib were modifiable, I could have implement cloneable but this is not possible since I can't modify them. 如果外部库中的类是可修改的,那么我可以实现可克隆的,但这是不可能的,因为我无法修改它们。
You should create a defensive copy of the mutable instance: 您应该创建可变实例的防御性副本:
class A {
private final B b;
public A(B b) {
// Create a defensive copy of b
this.b = new B(b);
}
}
If B
does not provide a copy constructor like this, you will need to implement defensive copying for B
on your own. 如果B
没有提供这样的复制构造函数,则您将需要自己为B
实现防御性复制。
If you don't do this, I can pass an instance of B
to A
, but also keep that instance of B
to myself and mutate it later on at my own will. 如果你不这样做,我可以通过实例B
到A
,而且还保持该实例B
对自己和我自己的意愿,后来发生变异它。
Class A should not allow access to any mutable references. A类不应允许访问任何可变引用。
Here's what your class example would look like: 这是您的班级示例的样子:
class A {
private final B b;
public A(B b) {
this.b = b;
}
// no public access to B reference that's final. No changing it from the outside. A is immutable.
}
Classes B, C, and D are from a library. 类B,C和D来自库。 If you give A a mutable reference and allow the rest of the code to change the state of B or its C and D children there's nothing to be done about that. 如果给A一个可变的引用并允许其余代码更改B或其C和D子代的状态,则无需执行任何操作。 But if you construct B properly and entrust it to A, then no one else will be able to alter its state. 但是,如果您正确构造B并将其委托给A,那么其他人将无法更改其状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.