码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-16 23:17:17      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   cti   

最近感觉做程序又开始浑浑噩噩,对设计模式和算法基本了解,但基本不会用。所以打算最近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;
            }
        }
    }

 

重头开始学23种设计模式:单例模式,布布扣,bubuko.com

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

标签:style   blog   color   io   for   cti   

原文地址:http://www.cnblogs.com/flyfish2012/p/3811505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!