public sealed class GoFSingleton { private static readonly GoFSingleton _instance = new GoFSingleton(); private GoFSingleton() { } public static GoFSingleton Instance { get { return _instance; } } }接下來即可在程式碼中以GoFSingleton gof = GoFSingleton.Instance;呼叫singleton物件
如果系統小,用到singleton可能只有一兩支class,那麼以上的singleton程式碼就只會有一兩支code duplication出現在系統內。
但當系統需要大量使用到singleton pattern時註1,duplication的情況就會比較多。以下提供一範例可使用泛型來實作出Singleton Pattern
public sealed class Singleton<T> where T : class, new() { private static readonly T _instance = new T(); private Singleton() { } public static T Instance { get { return _instance; } } }使用方式:SingletonObject obj = Singleton<SingletonObject>.Instance;
範例程式下載:SingletonPatternSample.zip
備註
1.關於Singleton Pattern濫用,Joshua Kerievsky在其著作Refactoring to Patterns(中文書名為重構-向範式前進)中Inline Singleton章節有詳細的說明
2.有關Singleton Pattern於threading的議題,可參考網友內向人推薦的好文Implementing the Singleton Pattern in C#
No comments:
Post a Comment