1.考虑用静态工厂方法代替构造器
静态工厂方法惯用名称
-
valueOf —— 类型转换方法
-
of —— valueOf的一种更简洁的替代
-
getInstance —— 该方法没有参数,并返回唯一的实例
-
newInstance —— 确保返回的每个实例都与其他实例不同
-
getType —— 与getInstance一样,但在工厂方法处于不同的类中使用,Type表示工厂方法所返回的对象类型
-
newType —— 与newInstance一样,但在工厂方法处于不同的类中使用,Type表示工厂方法所返回的对象类型
-
具体方法参考Boolean,EnumSet
2.遇到多个构造器参数时考虑用构建器
**代码实例 **
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
private int servingSize;
private int servings;
private int calories = 0;
private int fat = 0;
private int sodium = 0;
private int carbohydrate = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val) {
calories = val;
return this;
}
public Builder fat(int val) {
fat = val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
}
public Builder sodium(int val) {
sodium = val;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
public NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
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 static void main(String[] args) {
NutritionFacts nutritionFacts = new Builder(1, 3).calories(2).carbohydrate(2).build();
System.out.println(nutritionFacts.getCalories());
System.out.println(nutritionFacts.getCarbohydrate());
System.out.println(nutritionFacts.getFat());
System.out.println(nutritionFacts.getServings());
}
}
3.用私有构造器或枚举类型强化Singleton属性
代码实例
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() {}
private static Elvis getInstance() {
return INSTANCE;
}
}
public enum Elvis {
INSTANCE;
}
4.通过私有构造器强化不可实例化的能力
参考Math,Array,Collections
代码实例
public class UnitityClass {
// 避免调用构造函数实例化
private UnitityClass() {
throw new AssertionError();
}
}
5.避免创建不必要的对象
代码实例
String s = new String("stringtte"); // 不要这样做
String s = "stringtte";
6.消除过期的对象引用
一般而言,只要类是自己管理内存,程序员就应该警惕内存泄露问题。
代码实例
public Object pop() {
if (size == 0) {
throw new EmptyStackException();
}
Object result = elements[--size];
elemtents[size] = null; //重点在这里
return result;
}
网友评论