单例模式

一、懒汉式,线程安全

特点:整个方法被synchronized修饰,不高效
public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
    }

    public static synchronized LazySingleton getInstance() {
        if (null == instance) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

二、双重检验锁

特点:双重检验是因为创建对象不是原子操作,JVM会对其进行指令重排优化,使用volatile可以禁止JVM指令重排优化
public class DoubleCheckSingleton {
    private static volatile DoubleCheckSingleton instance;

    private DoubleCheckSingleton() {
    }

    public static DoubleCheckSingleton getInstance() {
        if (null == instance) {
            synchronized (DoubleCheckSingleton.class) {
                if (null == instance) {
                    instance = new DoubleCheckSingleton();
                }
            }
        }
        return instance;
    }
}

三、静态内部类

特点:JVM的机制保证了线程安全,同时也是懒汉式的(推荐)
public class StaticCheckSingleton {
    private static class SingletonHolder {
        private static final StaticCheckSingleton instance = new StaticCheckSingleton();
    }

    public static StaticCheckSingleton getInstance() {
        return SingletonHolder.instance;
    }
}

四、饿汉式,线程安全

public class NonLazySingleton {
    private static final NonLazySingleton instance = new NonLazySingleton();

    private NonLazySingleton() {
    }

    public static NonLazySingleton getInstance() {
        return instance;
    }
}

五、枚举

特点:创建枚举默认就是线程安全的,而且还能防止反序列化和反射创建新的对象
public enum EnumSingleton {
    INSTANCE(new Date());
    private Date date;

    EnumSingleton(Date date) {
        this.date = date;
    }

    public Date getDate() {
        return date;
    }

    public static EnumSingleton getInstance() {
        return INSTANCE;
    }
}
posted @ 2019-08-27 15:40  FranChouChou  阅读(126)  评论(0)    收藏  举报