勤加载(饿汉模式)
1 public class EagerSingleton { 2 3 private EagerSingleton() { 4 } 5 6 private static EagerSingleton instance = new EagerSingleton(); 7 8 public static EagerSingleton getInstance() { 9 return instance; 10 } 11 }
勤加载(static块)
1 public class StaticBlockSingleton { 2 3 private StaticBlockSingleton() { 4 } 5 6 private static StaticBlockSingleton instance; 7 8 static { 9 instance = new StaticBlockSingleton(); 10 } 11 12 public static StaticBlockSingleton getInstance() { 13 return instance; 14 } 15 }
懒加载(double-checked locking using volatile)
1 public class DoubleCheckedSingleton { 2 3 private DoubleCheckedSingleton() { 4 } 5 6 private volatile static DoubleCheckedSingleton instance; 7 8 public static DoubleCheckedSingleton getInstance() { 9 10 if (instance == null) { 11 synchronized (DoubleCheckedSingleton.class) { 12 if (instance == null) { 13 instance = new DoubleCheckedSingleton(); 14 } 15 } 16 } 17 return instance; 18 } 19 }
懒加载(内部静态类)
1 public class InnerClassSingleton { 2 3 private InnerClassSingleton() { 4 } 5 6 private static class Holder { 7 private static InnerClassSingleton instance = new InnerClassSingleton(); 8 } 9 10 public static InnerClassSingleton getInstance() { 11 return Holder.instance; 12 } 13 }
懒加载(枚举)
1 public enum EnumSingleton { 2 3 INSTANCE; 4 5 private Singleton instance; 6 7 EnumSingleton() { 8 instance = new Singleton(); 9 } 10 11 public Singleton getInstance() { 12 return instance; 13 } 14 15 }