让我笔试吃亏"单例模式"
让我笔试吃亏的题目:单例模式。
因为是纯英文试卷,而且我从来没有用过单例模式。
答题时,有点儿懵了,竟然在类的实例构造函数里瞎写一番。
回来之后,终于静下来心,踏踏实实地学习了一下。记录在此。
这个应该很明显,保证一个类只有单一的实例,也就是说你无法通过New或CreateInstance来创建这个类的一个新实例。
2. 单例的好处在哪里?
当一个对象在程序内部只能有一个实例的时候,它可以保证我们不会重复创建,而是始终指向同一个对象。
3. 应用场景:
如(记录系统日志.log)
4. 参考文章:
《Implementing the Singleton Pattern in C#》
http://www.yoda.arachsys.com/csharp/singleton.html
simple thread-safety
// 密封类,不允许派生子类
public sealed class Singleton
{
static Singleton instance = null; // 静态实例
static readonly object padlock = new object(); // 静态只读锁
Singleton() { } // 私有的构造函数
// 公共的静态属性:获取类的实例
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
}
public sealed class Singleton
{
static Singleton instance = null; // 静态实例
static readonly object padlock = new object(); // 静态只读锁
Singleton() { } // 私有的构造函数
// 公共的静态属性:获取类的实例
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
}
not quite as lazy,
but thread-safe without using locks
// 密封类,不允许派生子类
public sealed class Singleton
{
static readonly Singleton instance = new Singleton(); // 静态只读实例
static Singleton() { } // 静态构造函数,用于是初始化 instance 变量
Singleton() { } // 实例构造函数
// 公共的静态属性:获取类的实例
public static Singleton Instance
{
get
{
return instance;
}
}
}
public sealed class Singleton
{
static readonly Singleton instance = new Singleton(); // 静态只读实例
static Singleton() { } // 静态构造函数,用于是初始化 instance 变量
Singleton() { } // 实例构造函数
// 公共的静态属性:获取类的实例
public static Singleton Instance
{
get
{
return instance;
}
}
}