Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实
例供外部访问,并且提供一个全局的访问点。
设计步骤
1.私有化需要用单例模式的类的构造器
2.在其内部产生该类的实例化对象,并将其封装成private static类型。
3.定义一个公开的静态方法返回该类的实例。
懒汉式(非线程安全)
懒汉式(线程安全)
饿汉式(线程安全)
- public class Singleton {
- private static Singleton instance = new Singleton();
- private Singleton (){}
- public static Singleton getInstance() {
- return instance;
- }
- }
饿汉式另一种实现方式(线程安全)
- public class Singleton {
- private Singleton instance = null;
- static {
- instance = new Singleton();
- }
- private Singleton (){}
- public static Singleton getInstance() {
- return this.instance;
- }
- }
静态内部类实现单例模式
- public class Singleton {
- private static class SingletonHolder {
- private static final Singleton INSTANCE = new Singleton();
- }
- private Singleton (){}
- public static final Singleton getInstance() {
- return SingletonHolder.INSTANCE;
- }
- }
运用枚举实现单例模式
- public enum Singleton {
- INSTANCE;
- public void whateverMethod() {
- }
- }
双重锁定实现单例模式
- 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;
- }
- }
以上就是DannyWu给大家讲解的Java中单例模式,如有问题请在下方评论出提出,我们一同讨论!

我的微信
有问题微信找我