Singleton pattern is creational design pattern that deals with object creation mechanisms, trying to create objects in a manner suitable to the situation.
PURPOSE:
The purpose of the Singleton class is to control object creation, limiting the number of objects to only one. Any instance fields of a Singleton will occur only once per class, just like static fields. Singletons are often used where you have to control the resources, such as database connections or sockets.
A perfect Singleton class should be :
- Thread safe
- Reflection proof
- Thread Safe:
If two threads try to initialize your Singleton class at almost the same time then it will create new object of Singleton class. To make it stop to create multiple object of your singleton class we have to make method synchronized.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class SingletonClass { private static SingletonClass mInstance; //private constructor. private SingletonClass(){ } public synchronized static SingletonClass getInstance(){ if (mInstance == null){ mInstance = new SingletonClass(); } return mInstance; } } |
2. Reflection proof:
Using reflection you can create multiple instance of your Singleton class to make your class reflection proof. To prevent Singleton failure while due to reflection you have to throw a run-time exception in constructor, if the constructor is already initialized and some class to initialize it again.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class SingletonClass { private static SingletonClass mInstance; //private constructor. private SingletonClass(){ //Prevent form the reflection api. if (mInstance != null){ throw new RuntimeException("Use getInstance() method to get the instance of the SingltonClass"); } } public static SingletonClass getInstance(){ if (mInstance == null){ mInstance = new SingletonClass(); } return mInstance; } } |
Now you can make your class a Singleton class that is thread, reflection.