单实例实践

 

 1、内部类

public class Singleton {
      private static class SingletonHolder {
             public static Singleton singleton = new Singleton();
      } 
       public Singleton getResource() {
              return SingletonHolder.singleton;
       }

        private Singleton() {};
}

 

 

 2、双重锁

 

public class Singleton() {
      private static volatile Singleton singleton = null;
      private Singleton() {};

      public static Singleton getSingleton() {
            if( singleton != null ) {
                   Synchronized(Singleton.class) {
                         if( singleton != null ) {
                                singleton = new Singleton();
                         }
                   }
            }
           return singleton;
      }
}

 

 

 3、非懒加载

public class Singleton() {
      private static Singleton singleton = new Singleton();
      private Singleton() {};

      public static Singleton getSingleton() {
            return singleton
      }
}

  

 4、枚举

 

你可能感兴趣的:(单例)