当我浏览下面的代码时,我找不到它在示例中使用私有(private)构造函数的原因?
public sealed class Singleton
{
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
...
//Why shouldnt I use something like below.
public class Singleton
{
private static Singleton instance = null;
static Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
如果我创建了一个静态类而不是公共(public)类,我可以直接使用该类而不是创建实例。
当静态关键字持续到同一个工作时,在这里创建私有(private)构造函数有什么需要?
遵循这种模式还有其他优势吗?
最佳答案
单例类和静态类是不同的东西,你似乎把它混为一谈了。静态类只有静态方法和静态成员,因此不能有构造函数。静态方法是在类型上调用的,而不是实例上。
相比之下,单例类具有普通方法并使用实例调用。私有(private)构造函数用于防止创建该类的多个实例,并且通常由返回此唯一实例的私有(private)属性使用。
public class Singleton
{
static Singleton s_myInstance = null;
private Singleton()
{
}
// Very simplistic implementation (not thread safe, not disposable, etc)
public Singleton Instance
{
get
{
if (s_myInstance == null)
s_myInstance = new Singleton();
return s_myInstance;
}
}
// More ordinary members here.
}
单例的优点是可以实现接口(interface)。此外,如果它们是有状态的(有很多成员),它们应该优于静态类,因为在静态类中有许多静态字段是非常丑陋的设计。
关于c# - 单例设计模式中私有(private)构造函数的需求是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36005348/