1. 程式人生 > >面試題(單例模式兩種寫法)

面試題(單例模式兩種寫法)

第一種形式:餓漢式單例

 public class Singleton {  
    private Singleton(){}  
    private static Singleton instance = new Singleton();  
     public static Singleton getInstance(){  
        return instance;  
    }  
 }  

第二種形式:懶漢式單例

public class Singleton {  
    private static Singleton instance = null;  
     private Singleton() {}  
     public static synchronized Singleton getInstance(){  
        if (instance==null) instance=newSingleton();  
        return instance;  
     }  
}  

區別:

<strong>“懶漢式”是在你真正用到的時候才去建這個單例物件,執行緒安全</strong>
<strong>“餓漢式”是在不管你用的用不上,一開始就建立這個單例物件:比如:有個單例物件,執行緒不安全</strong>