How can ENUM singleton a true singleton?
1. `public ENUM SingletonInstance{
INSTANCE;
doStuff(){
___________
}
}`
and we access it using SingletonInstance using SingletonInstance.INSTANCE.doStuff().
What about
2. `public ENUM SingletonInstance{
INSTANCE1, INSTANCE2;
doStuff(){
___________
}
}`
This voilates the single Pattern as we have 2 instances here.
When using class based singleton pattern,
3. `public class SingletonInstance{
doStuff(){
-----------
}
PSVM(){
SingletonInstance si = new SingletonInstance();
si.doStuff()
}
}
`
4. `public class SingletonInstance{
doStuff(){
------------
}
PSVM(){
SingletonInstance s1 = new Singleton();
s1.doStuff();
SingletonInstance s2 = new Singleton();
s2.doStuff();
}
}`
Now from the above 4 points, 1 and 3, if 1 is considered as Singleton, than point 3 has to be singleton. if point 3 is not a singleton, point 1 also cannot be singleton.. Point 2 and 4 are obivously not singleton..
`private SingletonInstance getInstance(){
if(instance == null){
instance = new SingletonInstance()
}
return instance;
}`
prevents 2nd instance fron bring created. hence this can be seen as truest form of Singleton pattern. Irresoective of any number of times we call getInstance() it is going to return me singleInstance.
Similarly, Irrespective of number of Constants, there should be only 1 instance of ENUM to be called as singleton..correct?
what about ENUM? is there any new way of prevent 2nd constant for ENUM? if yes, than that can be converted to purest form of singleton. But not, ENUMs cannot be considered singleton.
What's your say on this? Please help me understand ENUMs and how and why are they singletons if they don't prevent 2nd instance to be created.. ?
Expecting to understand ENUMs and how are the ENUMs singleton's without any enforcement.
Aucun commentaire:
Enregistrer un commentaire