The Singleton design pattern: you can never instantiate more than one. : Singleton « Design Pattern « Java Tutorial






Singleton provides a global access point
A singleton often has the characteristics of a registry or lookup service.
A singleton prevents the client programmer from having any way to create an object except the ways you provide. 
You must make all constructors private.
You must create at least one constructor to prevent the compiler from synthesizing a default constructor.
You provide access through public methods. 
Making the class final prevents cloning. 



final class Singleton {
  private static Singleton s = new Singleton(47);

  private int i;

  private Singleton(int x) {
    i = x;
  }

  public static Singleton getReference() {
    return s;
  }

  public int getValue() {
    return i;
  }

  public void setValue(int x) {
    i = x;
  }
}

public class SingletonPattern {

  public static void main(String[] args) {
    Singleton s = Singleton.getReference();
    String result = "" + s.getValue();
    System.out.println(result);
    Singleton s2 = Singleton.getReference();
    s2.setValue(9);
    result = "" + s.getValue();
    System.out.println(result);
  }
}








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