C#基础_单例模式

控制某个类型的实例数量-唯一一个

class Program
    {
        static void Main(string[] args)
        {
           test t1 = test.GetInstance();
           test t2 = test.GetInstance();
           Console.WriteLine(t1.GetHashCode()==t2.GetHashCode());

           Test T1 = new Test();
           Test T2 = new Test();
           Console.WriteLine(T1.GetHashCode()==T2.GetHashCode());
           Console.ReadKey();
        }
    }
    //单例模式
    public class test
    {
        private test() { }
        public static readonly test instance = new test();
        public static test GetInstance()
        {
            return instance;
        }

    }
    //普通类 
    public class Test
    {
    }

第一个哈希值相同,表明是一个实例;

第二个不同

posted @ 2016-06-15 14:56  shinchan  阅读(122)  评论(0编辑  收藏  举报