简体   繁体   English

如何使包含一系列Mutable类的类不可变?

[英]How to make a class containing series of Mutable classes Immutable?

I am aware about the basic rules of how to make object of a class immutable. 我知道有关如何使类的对象不变的基本规则。 However, my requirement is something like this. 但是,我的要求是这样的。 Say I have a class called School. 假设我有一堂课叫做School。 School has mutable class Rooms. 学校有可变的教室。 Rooms has mutable class Students. 房间里有可变的班级学生。 Students has mutable class Performance and so on. 学生有可变的班级表现等。 None of the classes implement Serializable. 没有一个类实现Serializable。 Now my requirement is to make the class School immutable.Also, if tomorrow School has another Mutable class chain (Say another mutable class Building), I need to retain immutability of School without much code change. 现在我的要求是使School类不可变。此外,如果明天School有另一个Mutable类链(比如说另一个可变的Class Building),则我需要在不进行大量代码更改的情况下保持School的不变性。

I know that this requirement can lead to infinite loop, but say after 5 level, we are OK to stop creating new objects to retain immutability. 我知道这个要求会导致无限循环,但是说在5级之后,我们可以停止创建新对象以保持不变性。

Can we use Reflection here? 我们可以在这里使用反射吗? Or is there any other way? 还是还有其他方法?

There is no real alternative other than having immutable versions of every class and copying them all the way down. 除了拥有每个类的不变版本并将其完全复制下来之外,没有其他真正的选择。

This will suck. 这会糟透了。

It's much easier to make all your types immutable from the beginning. 从一开始就使所有类型变得不可变要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM