1.考慮用靜態(tài)工廠方法代替構(gòu)造器
靜態(tài)工廠方法慣用名稱
valueOf —— 類型轉(zhuǎn)換方法
of —— valueOf的一種更簡潔的替代
getInstance —— 該方法沒有參數(shù)荠瘪,并返回唯一的實例
newInstance —— 確保返回的每個實例都與其他實例不同
getType —— 與getInstance一樣,但在工廠方法處于不同的類中使用,Type表示工廠方法所返回的對象類型
newType —— 與newInstance一樣司致,但在工廠方法處于不同的類中使用,Type表示工廠方法所返回的對象類型
具體方法參考Boolean胡野,EnumSet
2.遇到多個構(gòu)造器參數(shù)時考慮用構(gòu)建器
**代碼實例 **
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.用私有構(gòu)造器或枚舉類型強化Singleton屬性
代碼實例
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() {}
private static Elvis getInstance() {
return INSTANCE;
}
}
public enum Elvis {
INSTANCE;
}
4.通過私有構(gòu)造器強化不可實例化的能力
參考Math目锭,Array港谊,Collections
代碼實例
public class UnitityClass {
// 避免調(diào)用構(gòu)造函數(shù)實例化
private UnitityClass() {
throw new AssertionError();
}
}
5.避免創(chuàng)建不必要的對象
代碼實例
String s = new String("stringtte"); // 不要這樣做
String s = "stringtte";
6.消除過期的對象引用
一般而言秃嗜,只要類是自己管理內(nèi)存储玫,程序員就應(yīng)該警惕內(nèi)存泄露問題。
代碼實例
public Object pop() {
if (size == 0) {
throw new EmptyStackException();
}
Object result = elements[--size];
elemtents[size] = null; //重點在這里
return result;
}