辛格尔顿用C#实现的可能是这样的:静态属性和单例之间有什么区别?
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
如果我使用静态实现它想:
public static class Globals{
public static Singleton Instance = new Singleton();
}
这样
,应用程序还应该只得到一个实例整个应用程序。 那么这两种方法有什么区别?为什么不直接使用静态成员(更简单直接)?
我们需要声明*静态构造函数*在这里线程安全的? –
@CongLong不与'懒惰'版本。这是非常好的,它提供了适当的线程安全性和完美的懒惰实例化,并带有一个简单的API。 –
啊,是的,我明白了,+1 –