学习设计模式-创建型-单例模式

111 阅读1分钟

单例生成id自增方法

饿汉式

public class IdGenerator {

   private AtomicLong id = new AtomicLong(0);
   private static final IdGenerator instance = new IdGenerator();

   private IdGenerator() {
   }

   public static IdGenerator getInstance() {
      return instance;
   }

   public long getId() {
      return id.incrementAndGet();
   }
}

懒汉式

public class IdGenerator {

   private AtomicLong id = new AtomicLong(0);
   private static IdGenerator instance;

   private IdGenerator() {
   }

   public static synchronized IdGenerator getInstance() {
      if (instance == null) {
         instance = new IdGenerator();
      }
      return instance;
   }

   public long getId() {
      return id.incrementAndGet();
   }
}

双重检测

public class IdGenerator {

   private AtomicLong id = new AtomicLong(0);
   private static IdGenerator instance;

   private IdGenerator() {
   }

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

   public long getId() {
      return id.incrementAndGet();
   }
}

静态内部类

public class IdGenerator {

   private AtomicLong id = new AtomicLong(0);

   private IdGenerator() {
   }

   private static class SingletonHolder {
      private static final IdGenerator instance = new IdGenerator();
   }

   public static synchronized IdGenerator getInstance() {
      return SingletonHolder.instance;
   }

   public long getId() {
      return id.incrementAndGet();
   }
}

枚举

public enum IdGenerator {
   INSTANCE;

   private AtomicLong id = new AtomicLong(0);
   
   public long getId() {
      return id.incrementAndGet();
   }
}

from 争哥