现在的位置: 首页 > 综合 > 正文

Singleton单例模式,不用Lock的实现版本,限制条件是:被单例的类 必须有一个无参构造函数

2012年02月26日 ⁄ 综合 ⁄ 共 403字 ⁄ 字号 评论关闭

    /// <summary>
    /// 单例模式
    /// </summary>
    public sealed class Singleton<T> where T:new()
    {
        private Singleton() { }//防止new对象
        public static T Instance
        {
            get { return SingletonCreator.instance; }//延迟加载
        }
        internal class SingletonCreator
        {
            static SingletonCreator() { }
            internal static readonly T instance = new T();
        }
    }

调用方法  

你的类  obj=Singleton<你的类>.Instance;

抱歉!评论已关闭.