zoukankan      html  css  js  c++  java
  • C#设计模式:Singleton模式

    如何保证一个类只能有一个实例存在?
    在多线程情况下如何解决?
    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace Singleton
    {
        
    class Singleton
        
    {
            
    //构造函数私有化,保证不被显式实例化
            private Singleton() { }

            
    //定义属性,返回Singleton对象
            private static Singleton singleton;

            
    public static Singleton Instance
            
    {
                
    get
                
    {
                    
    if (singleton == null)
                        singleton 
    = new Singleton();
                    
    return singleton;
                }

            }

        }

    }


    //多线程版本的Singleton
    namespace SingletonMultiThread
    {
        
    class Singleton
        
    {
            
    private static object lockHelper = new object();

            
    //构造函数私有化,保证不被显式实例化
            private Singleton() {}

            
    //定义属性,返回Singleton对象
            private static volatile Singleton singleton = null;

            
    public static Singleton Instance
            
    {
                
    get
                
    {
                    
    if (singleton == null)
                    
    {
                        
    lock (lockHelper)
                        
    {
                            
    if (singleton == null)
                                singleton 
    = new Singleton();
                        }

                    }

                    
    return singleton;
                }

            }

        }

    }


    //经典的Singleton实现:仅仅适合无参构造器对象(可用属性实现扩展)
    namespace classicalSingleton
    {
        
    sealed class Singleton
        
    {
            
    private Singleton() { }
            
    //内联初始化,后面的new是个静态构造器
            public static readonly Singleton Instance = new Singleton();
        }


        
    class Program
        
    {
            
    static void Main(string[] args)
            
    {
                Singleton s1 
    = Singleton.Instance;
                Singleton s2 
    = Singleton.Instance;
                
    if (object.ReferenceEquals(s1, s2))
                    Console.WriteLine(
    "两个对象是相同的实例。");
                
    else
                    Console.WriteLine(
    "两个对象非相同的实例。");
            }

        }

    }

  • 相关阅读:
    Debian 9/Ubuntu 18添加rc.local开机自启的方法
    第一次使用Debian9所遇到的问题
    Open-Falcon注册时点击Sign up按钮没反应
    使用VMware虚拟机里的Ubuntu18.04部署RAID 10磁盘阵列
    Ubuntu18.04下Ansible的基本使用
    Go语言求水仙花数(for循环)
    自研模块加载器(四) 模块资源定位-异步加载
    自研模块加载器(三) module模块构造器设计-模块数据初始化
    自研模块加载器(二) 加载器结构与设计导论
    自研模块加载器(一) 模块系统概述与自定义模块规范书写规定
  • 原文地址:https://www.cnblogs.com/flaaash/p/1020841.html
Copyright © 2011-2022 走看看