大家一定用過或者看過“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 System.Threading.Mutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new