gpt4 book ai didi

java + 我应该使实例变量类不可变吗

转载 作者:行者123 更新时间:2023-12-01 04:40:36 26 4
gpt4 key购买 nike

来自http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html :

Don't provide "setter" methods — methods that modify fields or objects referred to by fields. Make all fields final and private. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods. If the instance fields include references to mutable objects, don't allow those objects to be changed: Don't provide methods that modify the mutable objects. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

名为 Employee 的类有一个 Address 类型的实例变量 a
我的问题:应该怎么做才能使此类不可变(条件:我想从 getAddress() getter 返回相同的实例变量 a)。
我应该使地址类不可变吗?

注意:我了解防御性副本,但不想使用它

最佳答案

您可以将员工地址作为最终变量,因此必须在构造函数执行完毕。所以你可以修改员工的构造函数,使其始终采用地址参数 n 初始化实例地址变量。一旦设置,你就无法将新的地址 obj 分配给已经初始化的地址变量。

关于java + 我应该使实例变量类不可变吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16638326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com