单例模式的多种实现方式

//需要时加锁,双重校验
class CustomSingleton{

   private static CustomSingleton customSingleton = null;

   private CustomSingleton(){};

   public static CustomSingleton getCustomSingleton(){
      if(customSingleton==null){
         synchronized (CustomSingleton.class) {
            if(customSingleton==null) {
               customSingleton = new CustomSingleton();
            }
         }
      }
      return customSingleton;
   }
}

/*
//需要时加锁,有并发问题
class CustomSingleton{

   private static CustomSingleton customSingleton = null;

   private CustomSingleton(){};

   public static CustomSingleton getCustomSingleton(){
      if(customSingleton==null){
         synchronized (CustomSingleton.class) {
            customSingleton = new CustomSingleton();
         }
      }
      return customSingleton;
   }
}*/

/*
//不加锁,有并发问题
class CustomSingleton{

   private static CustomSingleton customSingleton = null;

   private CustomSingleton(){};

   public static CustomSingleton getCustomSingleton(){
      if(customSingleton==null){
         customSingleton = new CustomSingleton();
      }
      return customSingleton;
   }
}*/

/*
//暴力同步锁
class CustomSingleton{

   private static CustomSingleton customSingleton = null;

   private CustomSingleton(){};

   public static synchronized CustomSingleton getCustomSingleton(){
      if(customSingleton==null){
         customSingleton = new CustomSingleton();
      }
      return customSingleton;
   }
}*/

/*
//线程安全  常量初始化
class CustomSingleton{

   private static CustomSingleton customSingleton = new CustomSingleton();

   private CustomSingleton(){};

   public static CustomSingleton getCustomSingleton(){ return customSingleton;}
}
*/

/*
//枚举单例
enum CustomSingleton{

   SINGLETON;

   public void print(){
      System.out.println(123);
   }
}*/

 

posted @ 2019-07-17 17:11  努力挣扎的小兵  阅读(161)  评论(0编辑  收藏  举报