创建型模式-单例模式

2017-02-07  本文已影响0人  顾树旺

单例模式简介

使用场景

角色

关键点

实现方式

优点

缺点

单例模式的具体实现

饿汉方式

public class Singleton {
  private static final Singleton sInstance = new Singleton();
  // ...

  public static Singleton getInstance() {
    return sInstance;
  }

  private Singleton() {
    // ...
  }
}

懒汉方式

public class Singleton {
  private static Singleton sInstance;
  // ...

  public static synchronized Singleton getInstance() {
    if (sInstance == null) {
      sInstance = new Singleton();
    }
    return sInstance;
  }

  private Singleton() {
    // ...
  }
}

Double CheckLock (DCL) 方式

public class Singleton {
  private static volatile Singleton sInstance;
  // ...

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

  private Singleton() {
    // ...
  }
}

静态内部类单例模式

public class Singleton {
  public static Singleton getInstance() {
    return SingletonHolder.sInstance;
  }

  private Singleton() {
    // ...
  }

  private static class SingletonHolder {
    private static final Singleton mInstance = new Singleton();
  }
}

枚举单例

public enum SingletonEnum {
  INSTANCE;
  public void doSomething() {
    // ...
  }
}

使用容器实现

public class SingletonManager {
  private static Map<String, Object> objMap = new HashMap<String, Object>();

  public static void registerService(String key, Object instance) {
    if (!objMap.containsKey(key)) {
      objMap.put(key, instance);
    }
  }

  public static Object getService(String, key) {
    return objMap.get(key);
  }

  private SingletonManager() {
  }
}
上一篇下一篇

猜你喜欢

热点阅读