Reputation: 11968
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?
Upvotes: 3
Views: 8021
Reputation: 25874
First, singletonobj
is a wrong/confusing name. Singletons are called on a class basis, like:
Log::getInstance().doSomething();
and not
Log log = new Log;
log.getInstance().doSomething();
So this should answer the question, but I'll detail anyway :)
Log::doSomething();
would force doSomething()
to be a static method, while
Log::getInstance().doSomething();
has 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 the getInstance()
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.
class SingletonExample {
private:
static SingletonExample* instance = NULL;
SingletonExample() { }
public:
static SingletonExample getInstance() {
if (instance == NULL) {
instance = new SingletonExample;
}
return *instance;
}
void doSomething() {
// Do something :)
}
}
Upvotes: 2
Reputation: 258628
Well, technically, singletonobj.getinstance()
is redundant, because that means you already got a hold of the object.
The call would usually look something like:
SingletonClass::getinstance().dosomething();
or
singletonobj.dosomething()
in case you pre-fetched the object - i.e. previously did
SingletonClass& singletonobj = SingletonClass::getinstance();
Upvotes: 9
Reputation: 5226
It would appear that that the first example is calling a regular method, whereas the second example is calling a static method.
The Singleton design pattern ensures that only a single instance of a given object is instantiated at any given time. The first example returns said instance, and then calls a method using an instance of an object.
The second example appears to be using a static method that does not require an instance of an object and actually invalidates the singleton design pattern...
Upvotes: 1