September 30, 2011

Singleton Design Pattern code example in Java

Singleton Class

public class SingletonClass {

   private static SingletonClass uniqueInstance;
   // other variables here

   private SingletonClass() { }

   public static synchronized SingletonClass getInstance() {

      if (uniqueInstance == null)
         uniqueInstance = new SingletonClass();
      return uniqueInstance;
   }

   // other methods here
}

2 comments:

  1. class Singleton
    {
    private static Singleton instance;
    private Singleton(String s)
    {
    //...
    System.out.println("......Instance....." +s);
    }

    public static synchronized Singleton getInstance(String s)
    {
    if (instance == null)
    instance = new Singleton(s);

    return instance;
    }
    //...
    public void doSomething()
    {
    //...
    }


    }

    public class SingletonClass {

    public static void main(String [] args) {
    try {

    Singleton con = Singleton.getInstance("first"); //ok

    }catch(Exception e) {
    System.out.println("first: " +e.getMessage());
    }

    try {
    Singleton con2 = Singleton.getInstance("second"); //failed.
    }
    catch(Exception e) {
    System.out.println("second: " +e.getMessage());
    }
    }

    // other methods here
    }

    ReplyDelete