Basic Singleton : Singleton « Design Pattern « Java Tutorial






public class BasicSingleton {

  static Singleton s1 = null, s2 = null;

  public static void main(String[] args) {
    s1 = Singleton.getInstance();
    s2 = Singleton.getInstance();

  }

}

class Singleton {
  private static Singleton mySingleton = null;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    if (null == mySingleton) {
      mySingleton = new Singleton();
      System.out.println(mySingleton.toString());
    } else {
      System.out.println(mySingleton.toString());

    }
    return mySingleton;

  }
}








34.1.Singleton
34.1.1.Basic Singleton
34.1.2.The Singleton design pattern: you can never instantiate more than one.
34.1.3.Singleton test
34.1.4.Synchronized Singleton
34.1.5.Singleton Factory