单例模式

1. 双向锁定 线程安全

class SingletonClass

{

public static SingletonClass SingletonClass { get; set; }

public readonly static object locker = new object();

private SingletonClass()

{ }

public static void CreateSingletonClassInstance()

{

if (SingletonClass == null)

{

lock (locker)

{

SingletonClass instanceClass = new SingletonClass();

if (SingletonClass == null)

{

SingletonClass = instanceClass;

}

}

}

}

}

2. 用到了readonly字段编译时初始化的性质 线程安全

sealed class SingletonClass

{

public readonly static SingletonClass singletonClass;

private SingletonClass()

{ }

static SingletonClass()

{

if (singletonClass == null)

singletonClass = new SingletonClass();

}

}

你可能感兴趣的:(单例模式)