单例模式的几种写法

一、饿汉式

特性:立即创建 线程安全 没有延迟加载

    public class Single {
        private static Single instance=new Single();
        private Single(){}
        public static Single getInstance(){
             return instance;   
        }
   }

二、懒汉式

特性:延迟创建,线程不安全

    public class Single {
    private static Single instance;
    private Single(){}
    public static Single getInstance(){
        if(instance==null){
            instance=new Single();
        }
        return instance;    
    }
    }

三、加锁的懒汉式

特性:延迟创建 线程安全 同步情况下效率低

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

四、双重验证式懒汉式

特性:延迟创建 线程安全 同步情况下效率高

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

五、类加载方式

特性:延迟创建 线程安全 同步情况下效率高

    public class Single {
    private Single(){}
    private static class ClassHolder{
        private static Single instance=new Single();
    }
    public static Single getInstance(){
        return ClassHolder.instance;        
    }
    }

六、枚举方式

特性:原生防止反射和反序列化击穿

    public enum Single{
        INSTANCE;
    }

你可能感兴趣的:(单例模式的几种写法)