阅读量:0
在Java中实现单例模式有多种方式,以下是其中几种常用的实现方式:
- 饿汉式(线程安全):
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }
- 懒汉式(线程不安全):
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
- 懒汉式(线程安全,双重检查锁定):
public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
- 静态内部类(线程安全):
public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
以上是几种常用的单例模式实现方式,选择哪种方式取决于具体的需求和线程安全性要求。