ars*_*upn 3 singleton constructor design-patterns private
我只是想学习设计模式.所以我分析源代码,但无法弄清楚为什么私有构造函数在单例模式中使用.任何人都可以帮我理解原因吗?
假设您有一个像这样定义的单例类(代码在C#上,但无关紧要):
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以有两个类的实例:
var instance1 = Singleton.Instance;
var instance2 = new Singleton();
Run Code Online (Sandbox Code Playgroud)
但模式本身是为了避免多个副本.
http://csharpindepth.com/articles/general/singleton.aspx