• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

singleton pattern

 
Ranch Hand
Posts: 662
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic