Java五种单例模式

懒汉式: 延迟加载,线程安全,调用效率不高

public class LazySingleton {
    private LazySingleton(){}

    private static LazySingleton lazySingleton;

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

饿汉式: 不能延迟加载,线程安全。调用效率高。

public class HungrySingleton {
    private  HungrySingleton(){}
    
    private static  HungrySingleton hungrySingleton=new HungrySingleton();
    
    public static  HungrySingleton getInstance(){
        return hungrySingleton;
    }
}

双重校验模式: 线程安全,但是由于加锁会造成性能下降。延迟加载

public class DoubleCheckLock {
    private DoubleCheckLock(){}
    
    private volatile static DoubleCheckLock doubleCheckLock;
    
    public static DoubleCheckLock getInstance(){
        if(doubleCheckLock==null){
            synchronized (DoubleCheckLock.class){
                if(doubleCheckLock==null){
                    doubleCheckLock=new DoubleCheckLock();
                }
            }
        }
        return doubleCheckLock;
    }
}

静态内部类方式: 线程安全,延迟加载,调用效率高

public class StaticInnerClass {
    private StaticInnerClass() {
    }

    private static class Inner {
        private static StaticInnerClass staticInnerClass = new StaticInnerClass();
    }

    public static StaticInnerClass getInstance() {
        return Inner.staticInnerClass;
    }
}

枚举方式: 线程安全,调用效率高,但不能延迟加载。可以防止反射和反序列化。

public class Singletonenum {
    private Singletonenum() {
    }

    private enum Sing {
        INSTANCE;
        private Singletonenum singletonenum;

        private Sing() {
            singletonenum = new Singletonenum();
        }

        public Singletonenum getenum() {
            return singletonenum;
        }
    }

    public static Singletonenum getInstance() {
        return Sing.INSTANCE.getenum();
    }
}

你可能感兴趣的:(Java五种单例模式)