设计模式:单例模式

单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

懒汉式:

namespace SingletonDesign
{
    public class Singleton
    {
        private static Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            if(instance==null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}
View Code

测试代码:

            for(int i=0;i<100;i++)
            {
                Task.Run(() => {
                    Singleton s = Singleton.GetInstance();
                    Console.WriteLine(s.GetHashCode());
                });
            }
View Code

饿汉式:

namespace SingletonDesign
{
    public sealed class Singleton
    {
        private static readonly Singleton instance=new Singleton();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            return instance;
        }
    }
}
View Code

 

posted @ 2016-03-16 15:40  uptothesky  阅读(201)  评论(0编辑  收藏  举报