关于不可变类

use*_*269 1 java

我有以下查询,我正在通过Java不可变类概念,并提出以下分析..

  • 所有字段必须是私有的,最好是最终的
  • 确保不能覆盖类 - 使类最终,或使用静态工厂并保持构造函数私有
  • 必须从构造函数/工厂填充字段
  • 不要为字段提供任何setter
  • 留意收藏品.使用Collections.unmodifiable*.
  • 此外,集合应仅包含不可变对象
  • 所有getter必须提供不可变对象或使用防御性复制
  • 不提供任何更改Object内部状态的方法.

现在我有以下课程..

public final class Bill {

    private final int amount;
    private final DateTime dateTime;
    private final List<Integers> orders;

}
Run Code Online (Sandbox Code Playgroud)

请告知如何将其作为不可变类.

ass*_*ias 6

你的班级是不可改变的.现在您可能想要添加一些方法:

public final class Bill {

    private final int amount;
    private final DateTime dateTime;
    private final List<Integers> orders;

    public Bill(int amount, DateTime dateTime, List<Integer> orders) {
        this.amount = amount; //primitive type: ok
        this.dateTime = dateTime; //joda.DateTime is immutable: ok
        this.orders = new ArrayList<Integer> (orders); //make a copy as the caller could modify the list at its end
    }

    // no method that adds or removes from the list

   public List<Integer> getOrders() {
       return Collections.unmodifiableList(orders); //defensive copy
   }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以this.orders = Collections.unmodifiableList(orders);在构造函数中使用并从getOrders()返回它return orders;,这会强制您不应该修改该列表,即使在您的类中也是如此.