• c#单例模式


    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace 单例模式
    {
        class Program
        {
            static void Main(string[] args)
            {
                Singleton s1 = Singleton.GetInstance();
                Singleton s2 = Singleton.GetInstance();
    
                if (s1 == s2)
                {
                    Console.WriteLine("Objects are the same instance");
                }
    
                Console.Read();
            }
        }
    
    
        class Singleton
        {
            private static Singleton instance;
            private static readonly object syncRoot = new object();
            private Singleton()
            {
            }
    
            public static Singleton GetInstance()
            {
                if (instance == null)
                {
    
                    lock (syncRoot)//用锁来防止两个线程同时访问
                    {
    
                        if (instance == null)//因此还需要在判断一下,实例是否为空,比如第一个线程进来创建后,紧接着第二个线程进来就无法创建第二个实例了
                        {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
    
        }
    
        //public sealed class Singleton
        //{
        //    private static readonly Singleton instance = new Singleton();
        //    private Singleton() { }
        //    public static Singleton GetInstance()
        //    {
        //        return instance;
        //    }
        //}
    }
  • 相关阅读:
    程序片段--2的乘方
    Set、Map集合、栈、队列
    Map迭代(六种)
    Struts2标签--控制标签
    线性表
    数据结构笔记(1)
    spingMVC问题小结
    《浪潮之巅》十四章笔记
    《浪潮之巅》十三章笔记
    《浪潮之巅》十二章笔记
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4321500.html
Copyright © 2020-2023  润新知