设计模式:重读(单例)

对于单例,程序内使用有如下的区分:

1: 延迟加载型:

 1.1 : 单线程

 1.2 : 多线程 线程安全型 

2:非延迟加载型:

其中个人感觉,程序内大部分都是使用的延迟加载型。总结代码如下:

   /// <summary>
    /// 延迟型:单线程单例
    /// </summary>
    public class Singleton
    {
        private static Singleton instance = null;
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
        public int Value { get; set; }
    }

    /// <summary>
    /// 延迟型:多线程单例
    /// </summary>
    public class Singleton_MulThread
    {
        private static Singleton_MulThread instance = null;
        private static object lockHelper = new object();
        private Singleton_MulThread() { }
        public static Singleton_MulThread Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockHelper)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton_MulThread();
                        }
                    }
                }
                return instance;
            }
        }
        public int Value { get; set; }
    }

    /// <summary>
    /// 非延迟型: 因为初始化是.net Framwork控制的。不能具体控制程序,所以在简单的程序内使用是没问题的。线程安全 
    /// </summary>
    public sealed class Singleton_Static
    {
        static readonly Singleton_Static instance = new Singleton_Static();

        static Singleton_Static()
        {
        }

        Singleton_Static()
        {
        }

        public static Singleton_Static Instance
        {
            get
            {
                return instance;
            }
        }
    }


备注:请注意上面多线程的两个判断, 其中第一个判断是用来使多线程中的Lock次数变少,提高多线程性能而加入的。

         if (instance == null)
               {
                    lock (lockHelper)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton_MulThread();
                        }
                    }
                }

 

 

 

posted on 2014-04-14 17:08  为人为梦  阅读(119)  评论(0编辑  收藏  举报

导航