File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "singleton pattern" Watch "singleton pattern" New topic

singleton pattern

Jayadev Pulaparty
Ranch Hand

Joined: Mar 25, 2002
Posts: 662
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 {
static Singleton* Instance(); // gives back a real object!
static proof(void); // proof that the object was made
Singleton(); // constructor
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

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: singleton pattern
It's not a secret anymore!