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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Signleton{ | |
private static Singleton singleton | |
private Singleton(){ | |
//... do other intantiation stuff here.. | |
} | |
public static Singleton getInstance(){ | |
if(singleton == null){ | |
this.singleton = new Singleton(); | |
} | |
return singleton; | |
} | |
// other responsibities... | |
.. | |
... | |
} |
Examples:
- constants
- configuration
- cache
- datasource
No comments:
Post a Comment