Using C# 2.0 Generics to achieve a reusable Singleton pattern

来源:互联网 发布:nginx ssl 自签名证书 编辑:程序博客网 时间:2024/05/17 03:36

一般代码:

    public sealed class Singleton    {        Singleton()        {        }        public static Singleton Instance        {            get            {                return SingletonCreator.instance;            }        }                class SingletonCreator        {            // Explicit static constructor to tell C# compiler            // not to mark type as beforefieldinit            static Nested()            {            }            internal static readonly Singleton instance = new Singleton();        }    }
用模板实现:

    public class SingletonProvider <T> where T:new()    {        SingletonProvider() {}        public static T Instance        {            get { return SingletonCreator.instance; }        }        class SingletonCreator        {            static SingletonCreator() { }            internal static readonly T instance = new T();        }    }
用例:

    public class TestClass    {        private string _createdTimestamp;        public TestClass ()        {            _createdTimestamp = DateTime.Now.ToString();        }        public void Write()        {            Debug.WriteLine(_createdTimestamp);        }    }
使用:

SingletonProvider<TestClass>.Instance.Write();

原地址:


0 0
原创粉丝点击