【发布时间】:2018-04-23 04:00:20
【问题描述】:
我是一名 c# 开发人员。
我对单例模式中的私有构造函数和静态构造函数感到困惑。
下面是我的示例代码:
标准单例模式,它是线程安全的:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// singleton pattern
/// </summary>
private SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
第二次将私有构造函数改为静态构造函数:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// static(single object in our application)
/// </summary>
static SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
我的问题是第二个代码仍然是单例模式之一,还是它总是在我们的应用程序中保留一个对象(RedisCacheManager)? 有人帮帮我,谢谢。
【问题讨论】:
-
没有所谓的“静态构造函数”。
-
看看这个link
标签: constructor singleton