I have come across the singleton pattern.
I was unable to understand the difference between
singletonobj.getinstance().dosomething() //1st one
and
singletonobj.dosomething() //2nd one
What does getinstance() do, that isn’t being done in the second case?
First,
singletonobjis a wrong/confusing name. Singletons are called on a class basis, like:and not
So this should answer the question, but I’ll detail anyway 🙂
would force
doSomething()to be a static method, whilehas
doSomething()as an instance method.Why use
getInstance()? Because a singleton, by its very definition, should only have zero or one instances. By making the constructor for a singleton private and publishing thegetInstance()method, it allows you to control how many instances of this class there are. The private constructor is simply to avoid other classes to instance this class, which would defeat the purpose of this class being a singleton, as you wouldn’t be able to control how many instances of this class there are.