@Learner 因为这是一个面试问题,而且主要是在印度,他们要求写信给 Psuedo 代码来评估候选人的编码技能,我试着让自己穿上候选人的鞋子来给出答案。
随着编程语言的进步,设计模式已经发展了一段时间,Singleton 也不例外。我们可以通过多种方式使用 C# 创建 Singleton 类。我想展示一些我能记得的味道
1.没有线程安全的普通香草单例
public sealed class Singleton
{
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2. 带线程安全的单例
public sealed class Singleton_ThreadLock
{
Singleton_ThreadLock()
{
}
private static readonly object padlock = new object();
private static Singleton_ThreadLock instance = null;
public static Singleton_ThreadLock Instance
{
get
{
// Uses the lock to avoid another resource to create the instance in parallel
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_ThreadLock();
}
return instance;
}
}
}
}
3. Singleton - 双线程安全
public sealed class Singleton_DoubleThreadSafe
{
Singleton_DoubleThreadSafe()
{
}
private static readonly object padlock = new object();
private static Singleton_DoubleThreadSafe instance = null;
public static Singleton_DoubleThreadSafe Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_DoubleThreadSafe();
}
}
}
return instance;
}
}
}
4. Singleton - 早期初始化
public sealed class Singleton_EarlyInitialization
{
private static readonly Singleton_EarlyInitialization instance = new Singleton_EarlyInitialization();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton_EarlyInitialization()
{
}
private Singleton_EarlyInitialization()
{
}
public static Singleton_EarlyInitialization Instance
{
get
{
return instance;
}
}
}
5. Singleton - 使用 .Net 4.0+ 框架的延迟初始化
public sealed class Singleton
{
private Singleton()
{
}
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
}
注意事项:
- 好吧,很少有人使用反射创建类的实例(我在我的一个框架中做过),但他也可以避免。网络中很少有样本可以显示如何避免它
- 将 Singleton 类设置为密封的始终是最佳实践,因为它会限制开发人员继承该类。
- 市场上有很多 IOC 可以创建普通类的 Singleton 实例,而无需遵循上述 Singleton 实现。