首页 > 代码库 > 重头开始学23种设计模式:单例模式

重头开始学23种设计模式:单例模式

最近感觉做程序又开始浑浑噩噩,对设计模式和算法基本了解,但基本不会用。所以打算最近1个月把设计模式和算法重新,温故而知新下。

首先从程序开发经常涉及到的23种设计模式开始,希望这次能更加熟练的运用设计模式来加强自己的开发能力。

首先从单例模式开始:

单例模式在我的理解是对程序对象的缓存,防止不断new,保持对象唯一性,提高程序性能。

namespace SinglePattern {    class Program {        static void Main(string[] args) {            for (int i = 0; i < 100; i++)            {                Task.Run(() =>                {                    Singleton objSingleton = Singleton.GetInstance;                });            }            Console.Read();        }    }    public class Singleton    {        private static  Singleton _instance = null;        private static readonly  object _obj = new object();        private static bool _initialize = false;        private Singleton()        {                    }        public static Singleton GetInstance        {            get            {                ////第一种写法                if (_instance == null) {                    lock (_obj) {                        if (_instance == null) {                            _instance = new Singleton();                            Console.WriteLine("Create a singleton instance!");                        }                    }                }                            //第二种写法                //if (!_initialize)                //{                //    lock (_obj)                //    {                //        if (!_initialize)                //        {                //            _instance=new Singleton();                //            _initialize = true;                //            Console.WriteLine("Create a singleton instance!");                //        }                //    }                //}                return _instance;            }        }    }}

上面就是单例常用写法。但实际项目开发当中,我们不能对每一个类都要写成单例,所以解决这种情况,我就需要一个容器来保持单例。

把需要单例的对象保存进去。

下面是代码:

 

    public class Singleton    {        private static readonly IDictionary<Type, object> allSingletons;        static Singleton()        {            allSingletons=new Dictionary<Type, object>();        }        public static IDictionary<Type, object> AllSingletons        {            get            {                return allSingletons;            }        }    }    public class Singleton<T> : Singleton    {        private static T _instance;        public static T Instance        {            get            {                return _instance;            }            set            {                _instance = value;                AllSingletons[typeof (T)] = value;            }        }    }