Java Singleton Examples
Singleton is used when you want an object that can not be instantiated more than once. For example, you want to database connection object and you want this same object to be used through out the application. In this case, you will want to create a singleton class for this database connection object.
The following are three different ways to make a Singleton class in Java.
1. Using Enum for creating Singleton class, this is the easiest.
public enum EnumSingleton { INSTANCE; private int counter = 0; public synchronized void greeting() { System.out.println("EnumSingleton: Hello " + counter); counter++; } }
2. Static factory way of creating Singleton class.
public class StaticFactorySingleton { private static final StaticFactorySingleton INSTANCE = new StaticFactorySingleton(); //Initialized during class loading private StaticFactorySingleton(){} //To prevent creating another instance of Singleton public static StaticFactorySingleton getSingleton(){ return INSTANCE; } private int counter = 0; public synchronized void greeting() { System.out.println("StaticFactorySingleton: Hello " + counter); counter++; } }
3. Double checking for making sure a Singleton.
public class DoubleCheckSingleton { private static volatile DoubleCheckSingleton INSTANCE; private DoubleCheckSingleton(){} //To prevent creating another instance of Singleton public static DoubleCheckSingleton getInstance() { if (INSTANCE == null) { synchronized(DoubleCheckSingleton.class) { //double checking Singleton instance if (INSTANCE == null) { INSTANCE = new DoubleCheckSingleton(); } } } return INSTANCE; } private int counter = 0; public synchronized void greeting() { System.out.println("DoubleCheckSingleton: Hello " + counter); counter++; } }
Testing
public class SingletonTest { public static void main(String args[]) { EnumSingleton.INSTANCE.greeting(); EnumSingleton.INSTANCE.greeting(); DoubleCheckSingleton.getInstance().greeting(); DoubleCheckSingleton.getInstance().greeting(); StaticFactorySingleton.getSingleton().greeting(); StaticFactorySingleton.getSingleton().greeting(); } }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts