四种获取单例的方式

项目中经常会用到单例模式,这里总结一下

1饿汉式

public class Singleton  {
    //饿汉式
    private Singleton(){
        
    }
    private static Singleton singleton = new Singleton();
    public static Singleton getInstance(){
        return singleton;
    }
    
}

2懒汉式 线程安全的

public class Singleton {
    //懒汉式
    private Singleton(){
        
    }
    private static Singleton singleton = null;
    
    public static synchronized  Singleton getInstance(){
        if(singleton==null){
            return new Singleton();
        }
        return singleton;
    }

}

3双中校验 线程安全的

public class Singleton {
    //双重校验
     private Singleton(){
         
     }
     private static volatile Singleton singleton = null;
     
     public static Singleton getInstance(){
         if(singleton==null){
             synchronized(Singleton.class){
                 if (singleton==null) {
                    return new Singleton();
                }
             }
         }
        return singleton;
     }
}

4静态内部类也就是嵌套类 线程安全的

public class Singleton {
    
    private Singleton(){}
    
    private static class InstanceHolder{
        private static Singleton singleton = new Singleton();
    }
    public static Singleton getInstance(){
        return InstanceHolder.singleton;
    }

}

 

synchronized会影响服务性能,为什么会影响,不太清楚,以后懂了在补充。静态内部类(嵌套类)相比之下会好些
posted @ 2016-01-14 20:31  Mr、Bo  阅读(406)  评论(0编辑  收藏  举报