单例模式
单例模式
只在内存中创建一次,只有一个对象
示例代码
public class Single
{
private static readonly object lockObj = new object( );
private static Single single;
public static Single GetSingle( )
{
if (single != null) return single;//线程锁容易耗费时间,所以此处预先做一个判定
lock (lockObj)
{
if (single != null) return single;
single = new Single( );
return single;
}
}
另外一种方式:通过内部类+静态构造实现延迟初始化
public class Single
{
private static readonly object lockObj = new object( );
private static Single single;
public static Single GetSingle( )
{
return Nested.instance;
}
class Nested
{
static Nested() { }
internal static readonly Single instance = new Single();
}
}