单例各种实现代码 1. 懒汉式单例实现 ```java /** * 懒汉式单例 */ public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } } ``` 2. 饿汉式单例实现 ```java /** * 饿汉式单例 */ public class HungrySingleton { private static HungrySingleton instance = new HungrySingleton(); private HungrySingleton() { } public static HungrySingleton getInstance() { return instance; } } ``` 3. 双重检查锁定实现 ```java /** * 双重检查锁定实现 */ public class DoubleCheckLockSingleton { private volatile static DoubleCheckLockSingleton instance; private DoubleCheckLockSingleton() { } public static DoubleCheckLockSingleton getInstance() { if (instance == null) { synchronized (DoubleCheckLockSingleton.class) { if (instance == null) { instance = new DoubleCheckLockSingleton(); } } } return instance; } } ``` 4. 静态内部类实现 ```java /** * 静态内部类实现 */ public class InnerClassSingleton { private InnerClassSingleton() { } private static class SingletonHolder { private static InnerClassSingleton instance = new InnerClassSingleton(); } public static InnerClassSingleton getInstance() { return SingletonHolder.instance; } } ``` 5. 枚举类单例实现 ```java /** * 枚举类单例实现 */ public enum EnumSingleton { INSTANCE; public void doSomething() { // do something } } ``` 6. 容器单例实现 ```java /** * 容器单例实现 */ public class ContainerSingleton { private static Map<String, Object> container = new ConcurrentHashMap<String, Object>(); private ContainerSingleton() { } public static Object getInstance(String className) { Object instance = null; if (!container.containsKey(className)) { try { instance = Class.forName(className).getDeclaredConstructor().newInstance(); container.put(className, instance); } catch (Exception e) { e.printStackTrace(); } return instance; } else { return container.get(className); } } } ```
标签:实现,代码,private,class,instance,static,单例,public From: https://www.cnblogs.com/deepalley/p/17114718.html