美文网首页
常用单例

常用单例

作者: eirunye | 来源:发表于2017-10-25 16:03 被阅读22次

    1.双重校验

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

    2.懒汉式

    • 线程不安全
    public class Singleton{
    private static Singleton instance;
    private Singleton(){};
    public static synchronized Singleton getInstance(){
        if(null == instance){
           instance = new Singleton();
          }
        return instance;
     }
    }
    
    1. 饿汉式
    public class Singleton{
    private static Singleton instance = new Singleton();
    private Singleton(){};
    public static Singleton getInstance(){
       return instance; 
      }
    }
    

    相关文章

      网友评论

          本文标题:常用单例

          本文链接:https://www.haomeiwen.com/subject/evuitxtx.html