单例各种实现代码
单例各种实现代码 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); } } }
为什么懒汉式单例类成员是static的?
因为懒汉式单例类需要在类加载的时候就进行实例化,而类的静态成员变量会在类加载的时候进行初始化,所以把单例类的实例化对象定义为static类型能够保证在类加载的时候就进行实例化。
不是在getInstance时候实例化的吗?
getInstance方法会在类加载的时候就被JVM加载,保证其线程安全,如果不定义为static类型的话,getInstance方法在类加载的时候就不会被加载,等到调用getInstance才会加载,这样就不能保证线程安全了。
static是在类加载的时候实例化,不是在调用的时候实例化,所以把单例类的实例化对象定义为static类型能