設計模式 - 單例模式(Singleton)

1. 概述

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton. - wikipedia

單例模式:是一種對象創(chuàng)建型模式,用來確保程序中一個類最多只有一個實例,并提供訪問這個實例的全局點。

單例模式解決以下類似問題:

  • 如何樣保證一個類只有一個實例?
  • 如何輕松地訪問類的唯一實例?
  • 一個類如何控制它的實例化?
  • 如何限制一個類的實例數(shù)量?

單例模式的解決方案:

  • 隱藏類的構造方法,用private修飾符修飾構造方法.
  • 定義一個public的靜態(tài)方法(getInstance()) ,返回這個類唯一靜態(tài)實例。

2. 適用場景

以下場景可使用單例模式:

  • 某些管理類,保證資源的一致訪問性。
  • 創(chuàng)建對象時耗時過多或耗費資源過多,但又經(jīng)常用到的對象;
  • 工具類對象;
  • 頻繁訪問數(shù)據(jù)庫或文件的對象。

Android:

  • Context.getSystemService()

  • KeyguardUpdateMonitor.getInstance(mContext)

  • Calendar.getInstance()

  • ....

其他:

  • 日志操作類
  • 文件管理器
  • 數(shù)據(jù)庫的連接尺
  • ...

3.實現(xiàn)方式

3.1 餓漢式

餓漢式,故名思議,很餓,所以在類加載的時候就直接創(chuàng)建類的實例。

/**
 * Singleton class. Eagerly initialized static instance guarantees thread safety.
 */
public final class Singleton {

  /**
   * Private constructor so nobody can instantiate the class.
   */
  private Singleton() {}

  /**
   * Static to class instance of the class.
   */
  private static final Singleton INSTANCE = new Singleton();

  /**
   * To be called by user to obtain instance of the class.
   *
   * @return instance of the singleton.
   */
  public static Singleton getInstance() {
    return INSTANCE;
  }
}

優(yōu)點:

  • 多線程安全

缺點:

  • 內存浪費,類加載之后就被創(chuàng)建了實例,但是如果某次的程序運行沒有用到,內存就被浪費了。

小結:

  • 適合:單例占用內存比較小,初始化時就會被用到的情況。
  • 不適合:單例占用的內存比較大,或單例只是在某個特定場景下才會用到

3.2 懶漢式

? 懶漢式,故名思議,很懶,需要用的時候才創(chuàng)建實例。

/**
 * Singleton class. Eagerly initialized static instance guarantees thread safety.
 */
public final class Singleton {

  /**
   * Private constructor so nobody can instantiate the class.
   */
  private Singleton() {}

  /**
   * Static to class instance of the class.
   */
  private static final Singleton INSTANCE = null;

  /**
   * To be called by user to obtain instance of the class.
   *
   * @return instance of the singleton.
   */
  public static Singleton getInstance() {
    if (INSTANCE == null){
        INSTANCE = new Singleton();
    }
    return INSTANCE;
  }
}

優(yōu)點:

  • 內存節(jié)省,由于此種模式的實例實在需要時創(chuàng)建,如果某次的程序運行沒有用到,就是可以節(jié)省內存

缺點:

  • 線程不安全,分析如下

    線程1 線程2 INSTANCE
    public static Singleton getInstance() { null
    public static Singleton getInstance() { null
    if (INSTANCE == null){ null
    if (INSTANCE == null){ null
    INSTANCE = new Singleton(); object1
    return INSTANCE; object1
    INSTANCE = new Singleton(); object2
    return INSTANCE; object2

    糟糕的事發(fā)生了,這里返回2個不同的實例。

小結:

  • 適合:單線程,內存敏感的
  • 不適合:多線程

3.3 線程安全的懶漢式

/**
 * Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
 * mechanism.
 *
 * Note: if created by reflection then a singleton will not be created but multiple options in the
 * same classloader
 */
public final class ThreadSafeLazyLoadedSingleton {

  private static ThreadSafeLazyLoadedSingleton instance;

  private ThreadSafeLazyLoadedSingleton() {
  // to prevent instantiating by Reflection call
    if (instance != null) {
        throw new IllegalStateException("Already initialized.");
    }
  }

  /**
   * The instance gets created only when it is called for first time. Lazy-loading
   */
  public static synchronized ThreadSafeLazyLoadedSingleton getInstance() {
    if (instance == null) {
        instance = new ThreadSafeLazyLoadedSingleton();
    }
    return instance;
  }
}

優(yōu)點:

  • 多線程安全

缺點:

  • 執(zhí)行效率低,每個線程在想獲得類的實例時候,執(zhí)行getInstance()方法都要進行同步。而其實這個方法只執(zhí)行一次實例化代碼就夠了,后面的想獲得該類實例,直接return就行了。方法進行同步效率太低要改進。

小結:

  • 不建議使用此方法,后續(xù)介紹其他方法可兼顧內存和多線程安全.

3.4 線程安全的雙重檢查

/**
 * Double check locking
 * <p/>
 * http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
 * <p/>
 * Broken under Java 1.4.
 *
 * @author mortezaadi@gmail.com
 */
public final class ThreadSafeDoubleCheckLocking {

  private static volatile ThreadSafeDoubleCheckLocking instance;

  /**
   * private constructor to prevent client from instantiating.
   */
  private ThreadSafeDoubleCheckLocking() {
    // to prevent instantiating by Reflection call
    if (instance != null) {
      throw new IllegalStateException("Already initialized.");
    }
  }

  /**
   * Public accessor.
   *
   * @return an instance of the class.
   */
  public static ThreadSafeDoubleCheckLocking getInstance() {
    // local variable increases performance by 25 percent
    // Joshua Bloch "Effective Java, Second Edition", p. 283-284
    
    ThreadSafeDoubleCheckLocking result = instance;
    // Check if singleton instance is initialized. If it is initialized then we can return the instance.
    if (result == null) {
      // It is not initialized but we cannot be sure because some other thread might have initialized it
      // in the meanwhile. So to make sure we need to lock on an object to get mutual exclusion.
      synchronized (ThreadSafeDoubleCheckLocking.class) {
        // Again assign the instance to local variable to check if it was initialized by some other thread
        // while current thread was blocked to enter the locked zone. If it was initialized then we can 
        // return the previously created instance just like the previous null check.
        result = instance;
        if (result == null) {
          // The instance is still not initialized so we can safely (no other thread can enter this zone)
          // create an instance and make it our singleton instance.
          instance = result = new ThreadSafeDoubleCheckLocking();
        }
      }
    }
    return result;
  }
}

優(yōu)點:

  • 多線程安全

注意點:

  • jdk 1.5以下多線程安全不能實現(xiàn)

小結:

  • 可使用此方法,兼顧內存和多線程安全.

3.5 靜態(tài)內部類

public class Singleton {
    private Singleton() {
    }

    /**
     * 類級的內部類,也就是靜態(tài)的成員式內部類,該內部類的實例與外部類的實例
     * 沒有綁定關系,而且只有被調用到時才會裝載,從而實現(xiàn)了延遲加載。
     */
    public static Singleton getInstance() {
        return SingletonLazyHolder.instance;
    }

    private static class SingletonLazyHolder {
        /**
         * 靜態(tài)初始化器,由JVM來保證線程安全
         */
        private final static Singleton instance = new Singleton();
    }
}

優(yōu)點:

  • 多線程安全

注意點:

  • jdk 1.5以下多線程安全不能實現(xiàn)

小結:

  • 可使用此方法,兼顧內存和多線程安全.

3.6 枚舉

public enum EnumSingleton {

  INSTANCE;

  @Override
  public String toString() {
    return getDeclaringClass().getCanonicalName() + "@" + hashCode();
  }
}

小結:

  • 可使用此方法,兼顧內存和多線程安全.同時這個也是Effective Java推薦使用的方法。注意枚舉也是jdk 1.5開始加入的。

4.總結

單例占用內存比較小,初始化時就會被用到的情況 - 推薦使用方法 3.1

多線程安全和內存占用大,特定場景下采用,推薦使用方法 3.4.3.5,3.6. 使用時注意jdk的版本。個人推薦使用 3.4.3.5。

5.Android代碼實例

5.1 Dialer,使用方法3.2

packages/apps/Dialer/java/com/android/incallui/InCallPresenter.java

private static InCallPresenter sInCallPresenter;
/** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */
@VisibleForTesting
InCallPresenter() {}
public static synchronized InCallPresenter getInstance() {
    if (sInCallPresenter == null) {
      sInCallPresenter = new InCallPresenter();
    }
    return sInCallPresenter;
}

//其他無關代碼省略

5.2 Email,使用方法3.5

packages/apps/Dialer/java/com/android/incallui/InCallPresenter.java

public class NotificationControllerCreatorHolder {
    private static NotificationControllerCreator sCreator =
            new NotificationControllerCreator() {
                @Override
                public NotificationController getInstance(Context context){
                    return null;
                }
            };

    public static void setNotificationControllerCreator(
            NotificationControllerCreator creator) {
        sCreator = creator;
    }

    public static NotificationControllerCreator getNotificationControllerCreator() {
        return sCreator;
    }

    public static NotificationController getInstance(Context context) {
        return getNotificationControllerCreator().getInstance(context);
    }
}

有興趣的可以自己在找找案例看看。

6.有參數(shù)的單例

android上有很多需要Context參數(shù)的單例場景。先不要急,看看Android源碼的實例:

packages/apps/Email/src/com/android/email/EmailNotificationController.java

    private static EmailNotificationController sInstance;
    /** Singleton access */
    public static synchronized EmailNotificationController getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new EmailNotificationController(context, Clock.INSTANCE);
        }
        return sInstance;
    }

其實也很簡單嗎,但是這里面有個小問題,如果傳遞參數(shù)是敏感的,是需要替換的,那就需要在處理一下:

public final class Singleton {

    private Context context;
    private static volatile Singleton instance;

    private Singleton(Context context) {
        this.context = context;
        if (instance != null) {
            throw new IllegalStateException("Already initialized.");
        }
    }

    public static Singleton getInstance(Context context) {
        Singleton result = instance;
        if (result == null) {
            synchronized (Singleton.class) {
                result = instance;
                if (result == null) {
                    instance = result = new Singleton(context);
                }
            }
            //這里要注意重新賦值
            instance.context = context;
        }
        return result;
    }
}

鳴謝

  1. Initialization-on-demand holder idiom
  2. Singleton pattern
  3. Head First 設計模式
  4. java-design-patterns
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容