面试题目2:实现Singleton模式
题目:设计一个类,我们只能生成该类的一个实例。
解题考点:
- 对单例(Singleton)模式的理解
- 对C#基础语法的理解,如静态构造函数等
- 对多线程编程的理解
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance;
{
get
{
return Nested.instance;
}
}
class Nested
{
static Nested()
{
}
internal static readonly Singleton isntance = new Singleton();
}
}
上述代码中,我们在内部定义了一个私有类型Nested。当第一次用到这个嵌套类型时,会调用静态构造函数创建的实例instance。类型Nested只有在属性Singleton.Instance中被用到,由于其私有属性,他人无法使用Nested类型。