面試官:說(shuō)說(shuō)對(duì)單例模式的理解,最后的枚舉實(shí)現(xiàn)我居然不知
本文轉(zhuǎn)載自微信公眾號(hào)「Java極客技術(shù)」,作者鴨血粉絲 。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java極客技術(shù)公眾號(hào)。
一、介紹
說(shuō)起單例模式(Singleton Pattern),想必大家都不不會(huì)陌生,它是 Java 中最簡(jiǎn)單的設(shè)計(jì)模式之一,屬于創(chuàng)建型模式的一種,它提供了一種創(chuàng)建對(duì)象的最佳方式。
這種模式的意義在于保證一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)訪問(wèn)它的全局訪問(wèn)點(diǎn),避免重復(fù)的創(chuàng)建對(duì)象,節(jié)省系統(tǒng)資源。
二、實(shí)現(xiàn)思路
創(chuàng)建一個(gè)類,將其默認(rèn)構(gòu)造方法私有化,使外界不能通過(guò)new Object來(lái)獲取對(duì)象實(shí)例,同時(shí)提供一個(gè)對(duì)外獲取對(duì)象唯一實(shí)例的方法。
例如,創(chuàng)建一個(gè)SingleObject,如下:
- public class SingleObject {
- //創(chuàng)建 SingleObject 的一個(gè)對(duì)象
- private static SingleObject instance = new SingleObject();
- //讓構(gòu)造函數(shù)為 private,這樣該類就不會(huì)被實(shí)例化
- private SingleObject(){}
- //獲取唯一可用的對(duì)象
- public static SingleObject getInstance(){
- return instance;
- }
- public void showMessage(){
- System.out.println("Hello World!");
- }
- }
從 singleton 類獲取唯一的對(duì)象
- public class SingletonPatternDemo {
- public static void main(String[] args) {
- //不合法的構(gòu)造函數(shù)
- //編譯時(shí)錯(cuò)誤:構(gòu)造函數(shù) SingleObject() 是不可見(jiàn)的
- //SingleObject object = new SingleObject();
- //獲取唯一可用的對(duì)象
- SingleObject object = SingleObject.getInstance();
- //顯示消息
- object.showMessage();
- }
- }
執(zhí)行程序,輸出結(jié)果:
- Hello World!
三、單例模式的幾種實(shí)現(xiàn)方式
3.1、懶漢式,線程不安全(不推薦)
這種方式是最基本的實(shí)現(xiàn)方式,這種實(shí)現(xiàn)最大的問(wèn)題就是不支持多線程。因?yàn)闆](méi)有加鎖 synchronized,所以嚴(yán)格意義上它并不算單例模式。這種方式 lazy loading 很明顯,不要求線程安全,在多線程不能正常工作。
- public class Singleton {
- private static Singleton instance;
- private Singleton (){}
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
3.2、懶漢式,線程安全(不推薦)
這種方式具備很好的 lazy loading,能夠在多線程中很好的工作,但是,效率很低,99% 情況下不需要同步。優(yōu)點(diǎn):第一次調(diào)用才初始化,避免內(nèi)存浪費(fèi)。缺點(diǎn):必須加鎖 synchronized 才能保證單例,但加鎖會(huì)影響效率。getInstance() 的性能對(duì)應(yīng)用程序不是很關(guān)鍵(該方法使用不太頻繁)。
- public class Singleton {
- private static Singleton instance;
- private Singleton (){}
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
3.3、餓漢式(推薦使用)
這種方式比較常用,但容易產(chǎn)生垃圾對(duì)象。優(yōu)點(diǎn):沒(méi)有加鎖,執(zhí)行效率會(huì)提高。缺點(diǎn):類加載時(shí)就初始化,浪費(fèi)內(nèi)存。它基于 classloader 機(jī)制避免了多線程的同步問(wèn)題,不過(guò),instance 在類裝載時(shí)就實(shí)例化,雖然導(dǎo)致類裝載的原因有很多種,在單例模式中大多數(shù)都是調(diào)用 getInstance 方法, 但是也不能確定有其他的方式(或者其他的靜態(tài)方法)導(dǎo)致類裝載,這時(shí)候初始化 instance 顯然沒(méi)有達(dá)到 lazy loading 的效果。
- public class Singleton {
- private static Singleton instance = new Singleton();
- private Singleton (){}
- public static Singleton getInstance() {
- return instance;
- }
- }
3.4、雙檢鎖/雙重校驗(yàn)鎖(推薦使用)
這種方式采用雙鎖機(jī)制,安全且在多線程情況下能保持高性能。getInstance() 的性能對(duì)應(yīng)用程序很關(guān)鍵。
- 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;
- }
- }
3.5、靜態(tài)內(nèi)部類(推薦使用)
這種方式能達(dá)到雙檢鎖方式一樣的功效,對(duì)靜態(tài)域使用延遲初始化,但實(shí)現(xiàn)更簡(jiǎn)單。這種方式只適用于靜態(tài)域的情況,雙檢鎖方式可在實(shí)例域需要延遲初始化時(shí)使用。
- public class Singleton {
- private static class SingletonHolder {
- private static final Singleton INSTANCE = new Singleton();
- }
- private Singleton (){}
- public static final Singleton getInstance() {
- return SingletonHolder.INSTANCE;
- }
- }
3.6、枚舉(推薦使用)
這種實(shí)現(xiàn)方式還沒(méi)有被廣泛采用,但這是實(shí)現(xiàn)單例模式的最佳方法。它更簡(jiǎn)潔,自動(dòng)支持序列化機(jī)制,絕對(duì)防止多次實(shí)例化。這種方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不僅能避免多線程同步問(wèn)題,而且還自動(dòng)支持序列化機(jī)制,防止反序列化重新創(chuàng)建新的對(duì)象,絕對(duì)防止多次實(shí)例化。不過(guò),由于 JDK1.5 之后才加入 enum 特性,用這種方式寫(xiě)不免讓人感覺(jué)生疏,在實(shí)際工作中,也很少用。
- public enum Singleton {
- INSTANCE;
- public void doMethod() {
- }
- }
四、應(yīng)用
單例模式在Java中的應(yīng)用也很多,例如Runtime就是一個(gè)典型的例子,源碼如下:
- public class Runtime {
- private static Runtime currentRuntime = new Runtime();
- /**
- * Returns the runtime object associated with the current Java application.
- * Most of the methods of class <code>Runtime</code> are instance
- * methods and must be invoked with respect to the current runtime object.
- *
- * @return the <code>Runtime</code> object associated with the current
- * Java application.
- */
- public static Runtime getRuntime() {
- return currentRuntime;
- }
- /** Don't let anyone else instantiate this class */
- private Runtime() {}
- ...
- }
很清晰的看到,使用了餓漢式方式創(chuàng)建單例對(duì)象!
五、總結(jié)
一般情況下,不建議使用第 1 種和第 2 種懶漢方式,建議使用第 3 種餓漢方式。只有在要明確實(shí)現(xiàn) lazy loading 效果時(shí),才會(huì)使用第 5 種登記方式。如果涉及到反序列化創(chuàng)建對(duì)象時(shí),可以嘗試使用第 6 種枚舉方式。如果有其他特殊的需求,可以考慮使用第 4 種雙檢鎖方式。