Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor in Singleton pattern

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?

like image 608
arsnlupn Avatar asked Mar 23 '26 21:03

arsnlupn


2 Answers

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

like image 169
Anton Sizikov Avatar answered Mar 25 '26 13:03

Anton Sizikov


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.

like image 30
Bohemian Avatar answered Mar 25 '26 14:03

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!