Singleton Pattern
The Singleton pattern uses to prevent the instantiation of an Object or creating a new one. It is used when We need only one instance in the whole application. The singleton is similar to global variables and we can find many debates over singleton vs global variables on the internet. We can choose between singleton and global variables based on the application context, But global variables violate the encapsulation policy of OOP concepts.
Real Life Example:
The DataSource is very good example of a singleton pattern. We initialize DataSourcet object by some parameters like host,port,user and password. Every time We need the DataSource, the values of the parameters remains same So We need exactly one instance of DataSource.
Java Code Example:
There is the various implementation of the singleton, based on the initialization like eager, lazy, static block and thread safe. Below implementation called Bill Pugh Singleton Implementation is simplest and also thread safe.
package test; /** * Created by chaudharys on 12/4/17. */ public class DataSource { //Private Constructor, So No one can create new object private DataSource(){} private static class DataSourceHelper{ private static final DataSource dataSource = new DataSource(); } public static DataSource getInstance(){ return DataSourceHelper.dataSource; } }
Eager initialization
/** * Created by chaudharys on 12/4/17. */ public class DataSource { //Private Constructor, So No one can create new object private static final DataSource instance = new DataSource(); private DataSource(){} public static DataSource getInstance(){ return instance; } }
Thread Safe Lazy Initialization
package test; /** * Created by chaudharys on 12/4/17. */ public class DataSource { //Private Constructor, So No one can create new object private static DataSource instance; private DataSource(){} public static DataSource getInstance(){ if(instance == null){ synchronized (DataSource.class) { if(instance == null){ instance = new DataSource(); } } } return instance; } }
Destruction of Singleton:
We can destroy the singleton by using java reflection API's. Below is the example of breaking the above singleton code.
package test; import java.lang.reflect.Constructor; public class Test { public static void main(String args[] ){ DataSource d1 = DataSource.getInstance(); DataSource d2; try { Constructor[] constructors = DataSource.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { //Below code will destroy the singleton pattern constructor.setAccessible(true); d2 = (DataSource) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } } }
Comments
Post a Comment