美文网首页
单例模式(Singleton)

单例模式(Singleton)

作者: 毕加森 | 来源:发表于2018-03-07 15:55 被阅读0次
一、初始化单例类时即创建单例
  • 饿汉式:(线程安全)
public class Singleton {
  private static Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }
}
  • 枚举类型:(线程安全)
public enum Singleton {
  INSTANCE;
}
二、按需、延迟创建单例
  • 懒汉式:(线程不安全)
public class Singleton {
  private static Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}
  • 懒汉式(同步锁):(线程安全)
public class Singleton {
  private static Singleton instance = null;

  private Singleton() {
  }

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

  private Singleton() {
  }

  public static Singleton getInstance() {
    synchronized (Singleton.class) {
      if (instance == null) {
        instance = new Singleton();
      }
    }
    return instance;
  }
}
  • 懒汉式(双重校验锁):(线程安全)
public class Singleton {
  private static Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class) {
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}
  • 静态内部类:(线程安全)【推荐使用】
public class Singleton {
  private static class Singleton2 {
    private static Singleton instance = new Singleton();
  }

  private Singleton() {
  }

  public static Singleton getInstance() {
    return Singleton2.instance;
  }
}
单例模式的实现方式对比.png

原文:单例模式(Singleton)- 最易懂的设计模式解析

相关文章

网友评论

      本文标题:单例模式(Singleton)

      本文链接:https://www.haomeiwen.com/subject/lrvjfftx.html