Java单例模式

第一种:(早期初始化,效率高)

public class Singleton1 {

   private static Singleton1  one = new Singleton1();

 

   private Singleton1() {}

 

   public static Singleton1 getInstance() {

      return one;

  }

}

 

第二种:(懒散的载入,效率比第一种低,由于synchronized)

public class Singleton2 {

  private static Singleton2 two = null;

 

  private Singleton2() {}

 

  public static Singleton2 getInstance() {

     synchronized(Singleton2.this) {

        if (two == null) {

            two = new Singleton2();

        }

        return two;

     }

  }

}

你可能感兴趣的:(java,null,Class)