Java 单例模式

1、懒汉式——线程不安全

  1. public class SingletonOne {
  2. public static SingletonOne singleton;
  3. private SingletonOne() {}
  4. public static SingletonOne getSingleton() {
  5. if (singleton == null)
  6. return new SingletonOne();
  7. return singleton;
  8. }
  9. }

懒汉式实现了懒加载,但是线程不安全,基本不会使用。

2、懒汉式——线程安全

  1. public class SingletonTwo {
  2. public static SingletonTwo singleton;
  3. private SingletonTwo() {}
  4. public static synchronized SingletonTwo getSingleton() {
  5. if (singleton == null)
  6. return new SingletonTwo();
  7. return singleton;
  8. }
  9. }

在第一种的基础上加了个synchronized,保证线程安全,同时实现了懒加载,只是效率不高。

3、饿汉式

  1. public class SingletonThree {
  2. public static SingletonThree singleton = new SingletonThree();
  3. private SingletonThree () { }
  4. public static SingletonThree getSingleton() {
  5. return singleton;
  6. }
  7. }

由于实例优先提供,不存在线程安全问题,但是没有实现懒加载。

4、饿汉式——变种

  1. public class SingletonFour {
  2. public static SingletonFour singleton;
  3. static {
  4. singleton = new SingletonFour();
  5. }
  6. private SingletonFour () { }
  7. public static SingletonFour getSingleton() {
  8. return singleton;
  9. }
  10. }

其实和之前的一样,仅仅是将单例的创建挪到了静态块。

5、静态内部类式

  1. public class SingletonFive {
  2. private static class SingletonHolder {
  3. private static SingletonFive singleton = new SingletonFive();
  4. }
  5. private SingletonFive () {}
  6. public static final SingletonFive getSingleton(){
  7. return SingletonHolder.singleton;
  8. }
  9. }

静态内部类保证了懒加载,单例实例优先提供又保证了线程安全性,较实用。

6、枚举式

  1. public enum SingletonSix {
  2. SINGLETON;
  3. }

枚举的天然特性保证了单例,天然的私有构造器,天然的线程安全性,未被大规模使用的原因是枚举出现的有点晚。

7、双重校验锁式

  1. public class SingletonSeven {
  2. private static volatile SingletonSeven singleton;
  3. private SingletonSeven() {}
  4. public static SingletonSeven getSingleton(){
  5. if (singleton == null) {
  6. synchronized (SingletonSeven.class) {
  7. if (singleton == null)
  8. return new SingletonSeven();
  9. }
  10. }
  11. return singleton;
  12. }
  13. }

注意:

  1. volatile的使用,为了防止暴露一个未初始化的不完整单例实例;
  2. 双重判空校验,第一个判断避免了频繁的加锁,第二个判断可以拦住多余的创建实例的线程;
  3. 加锁,保证了线程安全(只有一个实例)

这种实现方式是经常出现在面试题中的,而且经常会要求手写。