单例各种实现代码

单例各种实现代码

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
getInstanceJVM线staticgetInstancegetInstance线
staticstatic
线
线饿getInstancesynchronized线 线 getInstancesynchronized线 synchronized线线 线线使synchronized线使线线线线Class线线线Class线synchronized线线getInstanceinstance线线线
 
 
 
posted @ 2023-02-12 20:57  八英里  阅读(21)  评论(0编辑  收藏  举报