日期:2008-09-29  浏览次数:20412 次

 

#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();
        }
    }
}