Rules :
- Constructor should be private.
- Private Static object of self should be declared in the class.
- This object should be initialized in a getInstance method
Example :
public class SingletonDemo { private static SingletonDemo obj; //1. Make a object of self private and static private SingletonDemo(){ //2. create a private constructor } public static SingletonDemo getInstance() { //3. create a static method that returns the instantiated method if(obj==null) { obj = new SingletonDemo(); } return obj; } }
What are the difference between a static class and a singleton class?
- A static class can not be a top level class and can not implement interfaces where a singleton class can.
- All members of a static class are static but for a Singleton class it is not a requirement.
- A static class get initialized when it is loaded so it can not be lazily loaded where a singleton class can be lazily loaded.
- A static class object is stored in stack whereas singlton class object is stored in heap memory space.
How to prevent cloning of a singleton object?
Throw exception within the body of clone() method