zoukankan      html  css  js  c++  java
  • 设计模式:重读(单例)

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

    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();
                            }
                        }
                    }
  • 相关阅读:
    标题
    Ubuntu配置 PPTP 服务器端
    网络虚拟化问题小记
    DevStack部署Openstack环境
    Ubuntu LVM扩展LV
    Gnocchi+Aodh服务简析
    部署Ceilometer +Gnocchi + Aodh
    Runing MAC on KVM 问题小记
    处理 Ceilometer UPD 丢包
    TC limit bandwidth
  • 原文地址:https://www.cnblogs.com/xiaolb/p/3664416.html
Copyright © 2011-2022 走看看