天天看點

Java中單例模式

單例模式,指的是一個類有且隻有一個執行個體。

單例模式主要作用是保證在Java應用程式中,一個類Class隻有一個執行個體存在。

單例模式主要有五種常用的建立方式,

一:懶漢式建立方式

特點:第一次調用才初始化,避免記憶體浪費。

/*
	 * 懶漢式建立單例模式 由于懶漢式是非線程安全, 是以加上線程鎖保證線程安全
	 */
	private static Play play = null;

	public static synchronized Play getPlay() {
		if (play == null) {
			play = new Play();
		}
		return play;
	}
           

二:餓漢式建立方式

特點:類加載時就初始化,線程安全

// 構造方法私有化
	private Play() {
		
	}

	// 餓漢式建立單例對象
	private static Play play = new Play();

	public static Play getPlay() {
		return play;
	}
           

三:雙重檢驗鎖(double check lock)(DCL)

特點:安全且在多線程情況下能保持高性能

public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
}
           

四:靜态内部類

特點:效果類似DCL,隻适用于靜态域

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}
           

五:枚舉

特點:自動支援序列化機制,絕對防止多次執行個體化

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}