zoukankan      html  css  js  c++  java
  • Singleton 模式

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace SingletonB
    {
        //class SingletonB
        //{
        //    private static SingletonB instance;
        //    private SingletonB()
        //    {

        //    }
        //    public static SingletonB GetInstance()
        //    {
        //        if (instance == null)
        //        {
        //            instance = new SingletonB();
        //        }
        //        return instance;
        //    }
        //}
        //多线程Singleton.
        class SingletonB
        {
            private static SingletonB instance;
            private static readonly object syncObj = new object();
            private SingletonB()
            {

            }
            public static SingletonB GetInstance()
            {
                if (instance == null)
                {
                    lock (syncObj)
                    {
                        if (instance == null)
                        {
                            instance = new SingletonB();
                        }
                    }
                }
                return instance;
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                SingletonB s1 = SingletonB.GetInstance();
                SingletonB s2 = SingletonB.GetInstance();

                if (s1 == s2)
                {
                    Console.WriteLine("the same instance!");
                }
                Console.ReadLine();
            }
        }
    }

    //饿汉式Singleton

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        private Singleton()
        {

        }
        public static Singleton GetInstance()
        {
            return instance;
        }
    }

  • 相关阅读:
    Windows10远程桌面连接提示:出现身份验证错误,要求的函数不受支持
    mybatis 中 if-test 判断大坑
    hutool的DateUtil工具类
    SpringBoot启动过程
    数据库事务的隔离级别
    EasyUI管理后台模板(附源码)
    springmvc中自定义拦截器以及拦截器的执行过程
    文件上传(MultipartFile)
    文件下载(使用springmvc框架中ResponseEntity对象)
    json格式实现数据传输
  • 原文地址:https://www.cnblogs.com/MayGarden/p/1516813.html
Copyright © 2011-2022 走看看