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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With