zoukankan      html  css  js  c++  java
  • 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;
        //    }
        //}
    }
  • 相关阅读:
    最长回文子串 leetcode
    leetcode Plus one
    n的阶乘末尾有几个0?
    求两数的最大公约数和最小公倍数
    汉诺塔
    求n的阶乘
    svn book
    求斐波那契数列第n项
    判断一个数是否是素数
    <C Traps and Pitfalls>笔记
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4321500.html
Copyright © 2011-2022 走看看