【140、java单例模式——详解JAVA单例模式及8种实现方式】

202 阅读2分钟

单例模式是设计模式中的一种,它保证一个类只有一个实例,并提供一个全局访问点。在Java中,单例模式通常有以下8种实现方式:

  1. 饿汉式(静态常量):在类加载时就创建实例对象,并通过静态常量的方式提供全局访问点。
public class Singleton {
    private static final Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}
  1. 饿汉式(静态代码块):在类加载时就创建实例对象,并通过静态代码块的方式提供全局访问点。
public class Singleton {
    private static final Singleton instance;
    static {
        instance = new Singleton();
    }
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}
  1. 懒汉式(线程不安全):在第一次使用时创建实例对象,并通过synchronized关键字保证线程安全。
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 懒汉式(线程安全,同步方法):在第一次使用时创建实例对象,并通过同步方法保证线程安全。
csharpCopy code
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 懒汉式(线程安全,双重检查锁):在第一次使用时创建实例对象,并通过双重检查锁保证线程安全。
public class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 懒汉式(线程安全,静态内部类):在第一次使用时创建实例对象,并通过静态内部类的方式保证线程安全。
public class Singleton {
    private Singleton() {}
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚举:通过枚举类型实现单例模式,枚举类型保证了实例的唯一性。
public enum Singleton {
    INSTANCE;
    public void doSomething() {
        // ...
    }
}
  1. ThreadLocal:为每个线程维护一个单例对象,保证线程安全。
public class Singleton {
    private static final ThreadLocal<Singleton> threadLocal = new ThreadLocal<Singleton>() {
        @Override
        protected Singleton initialValue() {
            return new Singleton();
        }
    };
    private Singleton() {}
    public static Singleton getInstance() {
        return threadLocal.get();
    }
}