java 幾種常見的單例模式

前言:直接介紹幾種線程安全的且我覺得還比較不錯的方式:
1.

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

    public static Singleton getInstance()  
    {  
        return instance ;  
    }  
}  

2、懶漢

public class Singleton02  
{  
    private static Singleton02 instance;  

    public static Singleton02 getInstance()  
    {  
        if (instance == null)  
        {  
            synchronized (Singleton02.class)  
            {  
                if (instance == null)  
                {  
                    instance = new Singleton02();  
                }  
            }  
        }  
        return instance;  
    }  
}  

3、使用一個持有類,主要是爲了不在初始化的時候加載

public class Singleton04  
{  
    private static final class InstanceHolder  
    {  
        private static Singleton04 INSTANCE = new Singleton04();  
    }  

    public static Singleton04 getInstance()  
    {  
        return InstanceHolder.INSTANCE;  
    }  
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章