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;
        //    }
        //}
    }
  • 相关阅读:
    hdu 1312 ( Red and Black )
    hdu 1429 ( 胜利大逃亡(续) )
    zjut 小X的苹果
    hdu 1253 ( 胜利大逃亡 )
    许多事
    1198 ( Farm Irrigation )
    hdu 1241 Oil Deposits
    hdu 1242 ( Rescue )
    hdu 1240 ( Asteroids! )
    zoj2966 build the electric system
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4321500.html
Copyright © 2011-2022 走看看