Friday 21 June 2013

How to create a Singleton Class in java

//  Example of Singleton Pattern in java //


package com.singletondemo;


class SingletonDB {


public static volatile SingletonDB getInstance;


private SingletonDB() {

   if (getInstance != null) {


               throw (new RuntimeException("instance access only 

                            createInstance()"));


    }

}


public static SingletonDB createInstance() {


if (getInstance == null) {

synchronized (SingletonDB.class) {

if (getInstance == null) {

getInstance = new SingletonDB();

}

}

}

return getInstance;

}


}


public class Main {

public static void main(String[] args) {


SingletonDB db = SingletonDB.createInstance();

System.out.println(db);


}

}




No comments:

Post a Comment