之前學習單例模式,現在回憶了一下,記錄下關於單例模式的寫法:
懶漢式:
public class Singleton {
/*
* 單例模式:單個實例服務於整個應用
* 懶漢式單例:只有在第一次請求實例的時候創建,並且只在第一次創建後,以後不再創建該類的實例
*/
// 1.一個私有的指向自己的靜態變量
private static Singleton instance;
// 2.私有的構造方法,保證不能從外部創建對象
private Singleton(){}
// 3.公開的靜態工廠方法,返回該類的唯一實例(當發現沒有實例沒有初始化的時候才初始化)
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
System.out.println("創建Singleton類的實例");
}else {
System.out.println("實例已經創建,不能再創建");
}
return instance;
}
}
// 測試類
class Test{
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
}
}
餓漢式:
public class Singleton2 {
/*
* 惡漢單例模式:在類加載的時候就創建一個單例模式.
*/
// 1.私有的構造函數,確保不能在類的外部訪問該類的構造函數
private Singleton2(){
System.out.println("構造函數執行了");
}
// 2.私有的唯一的靜態實例變量,在類加載的時候就創建好單例對象
private final static Singleton2 instance = new Singleton2();
// 3.公開的靜態工廠返回此類的唯一實例
public static Singleton2 getInstance(){
return instance;
}
}
// 測試類
class Test2{
public static void main(String[] args) {
Singleton2 s = Singleton2.getInstance();
System.out.println(s);
Singleton2 s2 = Singleton2.getInstance();
System.out.println(s2);
System.out.println(Singleton2.getInstance());
System.out.println(Singleton2.getInstance());
}
}
這兩種單例模式在面試中比較容易給問到。而真正能理解這些單例模式的同學又不多,理解了,沒過多少天日子就又會忘的了。。