大家一定用过或者看过Singleton模式了吧
下面给出三种实现方法分别给出优缺点
方法一
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
优点简单明了
缺点耗费资源
方法二
public sealed class ClassicSingleton
{
private static ClassicSingleton instance;
private static object syncRoot = new Object();
private ClassicSingleton() { }
public static ClassicSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
//custom code
instance = new ClassicSingleton();
}
}
}
return instance;
}
}
}
优点节省资源
缺点代码冗长
方法三
public sealed class Singleton
{
static Singleton(){Instance = new Singleton();}
private Singleton(){}
public static Singleton Instance{get; private set;}
}
优点既节省资源又简单明了
缺点线程不安全
方法四
public class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance
private static SystemThreadingMutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new SystemThreadingMutex();
}
public static Singleton Acquire()
{
mutexWaitOne();
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutexReleaseMutex();
}
}
优点既节省资源又简单明了线程也安全了(一箭三雕)
缺点轻微冗长