• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton pattern

 
Jayadev Pulaparty
Ranch Hand
Posts: 662
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends,
I'm trying to learn patterns, so please bear with me for any gross mis-conceptions. I was looking at the following code given as an example for singleton -
class Singleton {
public:
static Singleton* Instance(); // gives back a real object!
static proof(void); // proof that the object was made
protected:
Singleton(); // constructor
private:
static Singleton* _singleton;
};
The following are the thoughts and doubts that sprung in my mind (please validate them) -
1) The reason why they have a class variable _singleton is providing the primary motive of having only one instance for this class; i also understand that the Instance() public method was explicitly provided which signifies the absence of a public constructor Singleton();
2) The reason why the constructor Singleton() is made protected is going to serve two purposes - I) to avoid the system from supplying a default constructor in the public domain of the class
II)In order to be able to create the Singleton object from the static Instance() method;
My question here is "why can't this Singleton() constructor be private, which can still be called form the static Instance() method (if i'm not wrong) of the class. What are we exactly gaining here by saying this as protected?? Is it anything to do with the classes that derive this singleton class??
Please clarify.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most constructors of Singletons in Java are in fact private - I suspect that might be possible in C++ (which your example is in), too.
But as you said, you might want to make the constructor protected to allow derivatives of the Singleton.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic