單例模式原理:
單例模式又叫做 Singleton模式,指的是一個類,在一個JVM裏,只有一個實例存在。
關鍵要實現三點:
1. 構造方法私有化,使得外部無法通過new 得到新的實例
2. 靜態屬性指向實例,使整個類只有一個實例屬性值
3. public static的 getInstance方法,返回第二步的靜態屬性,外部只能從該方法獲得實例
實現方法:
public class SingletonTest2 {
//構造函數私有
private SingletonTest2() {
}
//定義私有靜態屬性,指向生成的唯一實例
private static SingletonTest2 instance;
//外部可訪問的方法,返回私有靜態屬性
public static SingletonTest2 getInstance() {
if (null == instance) {
instance = new SingletonTest2();
}
return instance;
}
}