大家一定用過或者看過
下面給出三種實現方法
方法一
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)
{
//
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 System
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new System
}
public static Singleton Acquire()
{
mutex
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutex
}
}
優點
缺點
From:http://tw.wingwit.com/Article/program/net/201311/12245.html