Reputation: 59
I am just trying to learn design patterns. So I analyse source code but cannot figure out why private constructor is used in singleton pattern. Can anyone helps me to understand the reason?
Upvotes: 3
Views: 9908
Reputation: 949
Underlying principle of Singleton pattern is to allow creation of only one object of class throughout the lifetime of application.
Private constructors are required for Singleton classes so that objects of such classes cannot be instantiated from outside the class. If Singleton classes do not have private constructors, objects of such classes can be created from outside too and hence the class will no longer be Singleton class.
Upvotes: 1
Reputation: 9415
Any member function (or method) is made private so that only member functions of the class has access or control over it. So, constructor is made private so that only member functions can call the constructor and thus can create the object.
Since, getInstance or other similar method has knowledge whether the object is created or not and they decide when to create the object or call the constructor.
That is why, it is not public. It is not even protected which can allow derived class to call the constructor.
To make singleton pattern successful and meaningful, only one public function should call the constructor when required (which is getInstance or other similar method).
Upvotes: 1
Reputation: 9240
Suppose you have a singleton class defined like this (the code is on C# but it does not matter):
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
public Singleton() //with a public constructor
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
So you can have two instances of you class:
var instance1 = Singleton.Instance;
var instance2 = new Singleton();
But the pattern itself is done to avoid multiple copies.
http://csharpindepth.com/articles/general/singleton.aspx
Upvotes: 6
Reputation: 425083
Constructors with private
visibility may only be invoked from within the class itself - self-only construction is one of the attributes of a singleton class.
Upvotes: 2