Intent:
Make it impossible to create another instance of class (so, only one instance).
And, provide a global point of access to it.
How to make a class Singleton?
1) Make the constructor private. Wait, a sec! Private constructor!!?? can we even have a constructor privates? Yes, we can.2) Then, how do we create a object?
Allowing global access point ...
- We have a static method getInstance() that returns an instance of Singleton class.
And, use Signleton.getInstance() not Singleton singleton = new Singleton(); singleton.getInstance();
to create an object.
3) How does getInstance finds the object?
- declare a private static member of the same type as of Singleton, private to avoid access from outside the class.
- getIntsance checks of there is already an instance and return that instance, else creates a new instance and stores it in the instance variable so that the same can be returned every-time a new instance is requested for.
That's it!! (There are some other issues in Java, details in other blog.)
Wait, But how does it look like?
Pseudo-code:
Examples:
- constants
- configuration
- cache
- datasource
No comments:
Post a Comment