简体   繁体   English

Java 不可变 class 疑问

[英]Java immutable class doubt

I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance. I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance.

If you provide delegates to all the getters, but don't provide a getter for the field itself.如果您为所有 getter 提供代表,但不为字段本身提供 getter。 For example:例如:

public final class Foo {
   private Bar bar;

   public String getBarField1() { 
       return bar.getBarField1();
   }
   public String getBarField2() {
       return bar.getBarField2();
   }
}

But there is a thing to consider - how is the field created.但是有一点需要考虑——该字段是如何创建的。 If it is passed in constructor, then you have to create a copy of it rather than get the passed object, otherwise the creating code will have reference to the Bar instance and be able to modify it.如果在构造函数中传入,则必须创建它的副本而不是获取传递的 object,否则创建代码将引用Bar实例并能够对其进行修改。

  1. Make the variable private将变量设为私有
  2. Allow access to the fields of variable only via getters( getVarNameProperty1() , getVarNameProperty2() );仅允许通过 getter( getVarNameProperty1() , getVarNameProperty2() ) 访问变量的字段;
  3. Make class final in order to deny inheritance.使 class 最终化以拒绝 inheritance。 In the child class one can create a public getter.在子 class 中,可以创建一个公共 getter。

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

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