在 Java 中实施不可变 class

Implementation of Immutable class in Java

在我的应用程序中,我需要让我的 class 成为不可变的,但是在我的 class 中我有一个其他 class 的对象是可变的,任何人都可以给我建议实施。

伪代码:

Class A 我希望它是不可变的 class

class A {
    /* ... */ 

    //class B is mutable
    B b = new B();
    /* ... */ 
}

假设您需要从外部世界访问 b,您将需要包装 B 上的所有方法并在 A 中声明它们。 此外,将 b 作为构造函数参数,没有 getter/setter 方法。

class A{
   private final b;
   A(B b){
     this.b = b;    
   }
   public String getSomeValue(){
     return b.getSomeValue();
   }

}

编辑:请参阅 Hoopje 关于在构造函数中克隆 b 的评论。如果 clone 或复制构造函数在 B 上不可用,那么您必须在 A

中自己构造新的 B