我有以下查询,我正在通过Java不可变类概念,并提出以下分析..
现在我有以下课程..
public final class Bill {
private final int amount;
private final DateTime dateTime;
private final List<Integers> orders;
}
Run Code Online (Sandbox Code Playgroud)
请告知如何将其作为不可变类.
你的班级是不可改变的.现在您可能想要添加一些方法:
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;,这会强制您不应该修改该列表,即使在您的类中也是如此.
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |