首页 > 开发 > 综合 > 正文

C#2.0中用范型实现单例模式

2024-07-21 02:17:52
字体:
来源:转载
供稿:网友

 

#region using directives

using system;
using system.collections.generic;
using system.text;
using system.reflection;

#endregion

namespace genericssingleton
{
    /// <summary>
    /// 单例范型
    /// </summary>
    /// <typeparam name="t"></typeparam>
    public class singleton<t>
    {
        private static t _instance;

        public singleton()
        {
        }

        public static t instance
        {
            get
            {
                if (_instance == null)
                {  

                   //获得实例,使用这个方法的前提是t要有公有的、无参数的构造函数               

                   _instance = (t)system.activator.createinstance(typeof(t));
                }
                return _instance;
            }
        }
    }

    /// <summary>
    /// 要实现单例的类
    /// </summary>
    public class foo
    {
        private int count = 0;

        public int count
        {
            get
            {
                count++;
                return count;
            }
        }
    }

    /// <summary>
    /// 主函数
    /// </summary>
    class program
    {
        static void main(string[] args)
        {
            //连续调用三次如果值是递增的话说明三次调用都是同一个实例
            console.writeline(singleton<foo>.instance.count);
            console.writeline(singleton<foo>.instance.count);
            console.writeline(singleton<foo>.instance.count);

            console.readline();
        }
    }
}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表