标签:不可变 style 返回 div 类型 his 初始化 getc code
不可变对象在多线程的情形下是线程安全的。构建规则可参照如下代码中注释。
//类添加final修饰符,保证类不被继承 public final class ImmutableNutritionFacts { //所有成员变量必须私有,并且加上final修饰 private final int servingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate; private final List<String> list; //通过构造器初始化所有成员,进行深拷贝(deep copy) public ImmutableNutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate, List<String> list){ this.servingSize = servingSize; this.servings = servings; this.calories = calories; this.fat = fat; this.sodium = sodium; this.carbohydrate = carbohydrate; this.list = list.subList(0, list.size()); //deep copy(引用类型) } //不提供改变成员变量的方法,包括setter //在getter方法中,不要直接返回对象本身,而是克隆对象,并返回对象的拷贝 public int getServingSize() { return servingSize; } public int getServings() { return servings; } public int getCalories() { return calories; } public int getFat() { return fat; } public int getSodium() { return sodium; } public int getCarbohydrate() { return carbohydrate; } public List<String> getList() { return list.subList(0, list.size()); //返回对象的拷贝 } }
标签:不可变 style 返回 div 类型 his 初始化 getc code
原文地址:https://www.cnblogs.com/hello-yz/p/9854574.html