1:简单的单例模式
写一个静态方法,一个静态字段
private static Singleton _singleton = null;
public static Singleton CreateSingleton()
{
if (_singleton==null)
{
_singleton = new Singleton();
}
return _singleton;
}
2:通过静态构造函数或者静态字段的写的单例
静态构造函数
static Singleton2()
{
_singleton = new Singleton2();
}
private static Singleton2 _singleton = null;
public static Singleton2 CreateSingleton()
{
return _singleton;
}
静态字段
private static Singleton3 _singleton = new Singleton3();
public static Singleton3 CreateSingleton()
{
return _singleton;
}
3:多线程情况下可能会用到线程锁
增加一个只读的object对象确保多线程情况下每次只有一个线程进入
private static Singleton1 _singleton = null;
private static readonly object Singleton1_lcok = new object();
public static Singleton1 CreateSingleton()
{
lock (Singleton1_lcok)
{
if (_singleton == null)
{
_singleton = new Singleton1();
}
}
return _singleton;
}