1. 程式人生 > >常用的兩種單例模式

常用的兩種單例模式

//懶漢式單例類.在第一次呼叫的時候例項化自己   
public class Singleton {  
    private Singleton() {}  
    private static Singleton single=null;  
    //靜態工廠方法   
    public static Singleton getInstance() {  
         if (single == null) {    
             single = new Singleton();  
         }    
        return single;  
    }  
}  

//餓漢式單例類.在類初始化時,已經自行例項化   
public class Singleton1 {  
    private Singleton1() {}  
    private static final Singleton1 single = new Singleton1();  
    //靜態工廠方法   
    public static Singleton1 getInstance() {  
        return single;  
    }  
}