Effective Java讀書筆記(二)
阿新 • • 發佈:2019-02-01
通過私有構造器槍花不可例項化的能力
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for nonintantiability
private UtilityClass() {
throw new AssertionError();
}
... // Remainder omitted
}
- 顯示的構造器是私有的,不可以在類的外部訪問。
- AssertionError()不是必需的,但是可以避免無意中在類的內部訪問。
- 註釋可以幫助理解將建構函式設定成私有的原因。
私有的顯示構造器將導致一個類不能被子類化。因為所有的構造器都必須顯示或隱式的呼叫超類的構造器。
避免建立不必要的物件
class Person {
private final Date brithDate;
// Other fields, methods, and constructor omitted
// The starting and ending dates of the baby boom.
private static final Date BOOM_START;
private static final Date BOOM_END;
static {
Calendar gmtCal =
Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_START = gmtCal.getTime();
gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_END = gmtCal.getTime();
}
public boolean isBabyBoomer(){
return birthDate.compareTo(BOOM_START) >= 0 &&
birthDate.compareTo(BOOM_END) < 0;
}
}
消除過期的物件引用
記憶體洩露的常見來源:
- 自己管理記憶體。
- 快取
- 監聽器和其他回撥
避免使用終結方法
終結方法(finalizer):
- 不保證會被及時地執行
- 不保證被執行
當類的物件中封裝的資源確實需要終止,可以提供一個現實的終止方法,並要求改類的客戶端在每個例項不再有用的時候呼叫這個方法。
顯示的終止方法通常與try-finally結構結合起來使用,以確保及時終止。
// try-finally block guarentees execution of termination methods
Foo foo = new Foo(...);
try{
// Do what must be done with foo
...
} finally {
foo.terminate(); // Explicit termination method
}
終結方法的兩種用途:
- 當物件的所有者忘記呼叫顯示終止方法時,終結方法可以充當“安全網”。
- 與native peer有關。
終結方法鏈:如果類有終結方法,並且子類覆蓋了終結方法,子類的終結方法就必須手工呼叫超類的終結方法。
@Override protected void finalize() throws Throwable {
try{
... // Finalize subclass state
} finally {
super.finalize();
}
}