单例设计模式分为两种:

  1. 在类被加载时初始化对象,称为SingletonPattern
  • 在类被使用时初始化对象(延迟加载),称为LazySingletonPattern

SingletonPattern

  1. public class C09_SingletonPattern {
  2. private C09_SingletonPattern(){
  3. System.out.println("C09_SingletonPattern was created...");
  4. }
  5. //类被加载时创建实例
  6. private static C09_SingletonPattern instant = new C09_SingletonPattern();
  7. public static C09_SingletonPattern getInstant(){
  8. return instant;
  9. }
  10. //用于加速加载该类
  11. public static void load(){}
  12. }

LazySingletonPattern

  1. public class C10_LazySingletonPattern {
  2. private C10_LazySingletonPattern(){}
  3. private static class SingletonPatternHolder{
  4. private static C10_LazySingletonPattern instant = new C10_LazySingletonPattern();
  5. }
  6. public static C10_LazySingletonPattern getInstant(){
  7. return SingletonPatternHolder.instant;
  8. }
  9. }