Singleton模式,寫法整理。
第二版:簡單的線程安全
public sealed class Singleton
{
private static Singleton instance = null ;
private static readonly object padlock = new object() ;
Singleton()
{
}
public static Singleton Instance
{
get
{
lock ( padlock )
{
if ( instance == null )
{
instance = new Singleton() ;
}
return instance ;
}
}
}
}
第四版:不是Lazy方式,但線程安全又不需要Lock
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton() ;
// Explicit static constructor to tell C# compiler
// not to mark type as before field init
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance ;
}
}
}
第五版:完全Lazy實例
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as before field init
static Nested()
{
}
internal static readonly Singleton instance = new Singleton() ;
}
}
第六版:使用 .NET 4 的 Lazy<T> 型別
// using System.Lazy<T>
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>( () => new Singleton() ) ;
public static Singleton Instance { get { return lazy.Value ; } }
private Singleton()
{
}
}
參考資料:
http://weiyiao.pixnet.net/blog/post/30971305-%5Bc%...
http://csharpindepth.com/Articles/General/Singleto...
https://msdn.microsoft.com/en-us/library/ff650316....
文章標籤
全站熱搜
留言列表