單例模式 (Singleton Pattern)
C# 實作
非執行緒安全 Singleton
public sealed class NotThreadSafeSingleton
{
private static NotThreadSafeSingleton _instance = null;
private NotThreadSafeSingleton()
{
}
public static NotThreadSafeSingleton Instance
{
get
{
if (_instance == null)
{
_instance = new NotThreadSafeSingleton();
}
return _instance;
}
}
}簡單執行緒安全 Singleton
使用 Double-checked Locking 確保執行緒安全
不使用 Lock, 確保執行緒安全 (非 Lazy)
完整 Lazy 實例
使用 .NET 4 的 Lazy
結語
Last updated