• 【设计模式】单例模式Singleton


    一、单线程

        public class Singleton
        {
            private static Singleton instance;
            int x, y;
    
            private Singleton()
            {
            }
            public static Singleton Instance
            {
                get
                {
                    if( instance == null )
                    {
                        instance = new Singleton();
                    }
                    return instance;
                }
            }
    
            private Singleton( int x, int y )
            {
                this.x = x;
                this.y = y;
            }
    
            public static Singleton GetInstance(int x,int y)
            {
                if( instance == null )
                {
                    instance = new Singleton( x, y );
                }
                else
                {
                    instance.x = x;
                    instance.y = y;
                }
    
                return instance;
            }
        }

    二、适用于多线程

        public class MultiThreadSingleton
        {
            private static volatile MultiThreadSingleton instance = null;
    
            private static object lockHelper = new object();
    
            private MultiThreadSingleton()
            {
            }
    
            public static MultiThreadSingleton Instance
            {
                get
                {
                    if( instance == null )
                    {
                        lock( lockHelper )
                        {
                            if( instance == null )
                            {
                                instance = new MultiThreadSingleton();
                            }
                        }
                    }
                    return instance;
                }
            }
        }

    三、适用于多线程与单线程

        public class AllSingleton
        {
            public static readonly AllSingleton Instance = new AllSingleton();
    
            private AllSingleton()
            {
            }
        }

    四、一个线程安全,懒实现的方式

    public sealed class Singleton
    {
       
        private static readonly Lazy<Singleton> instanceHolder =
            new Lazy<Singleton>(() => new Singleton());
    
        private Singleton()
        {
            ...
        }
    
        public static Singleton Instance
        {
            get { return instanceHolder.Value; }
        }
    }
  • 相关阅读:
    vue 交互 跨域获取数据
    计算属性computed缓存 与 methods 的思考
    _this 与 this
    python 占位符 %s Format
    odoo 中字段属性对象Field
    安装CentOS7.7图解
    docker的volumes
    Docker常用命令详解
    Ubuntu修改时区和更新时间
    SqlServer创建时间维度
  • 原文地址:https://www.cnblogs.com/xuxml/p/16184330.html
Copyright © 2020-2023  润新知