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;
        }
    }

  • 相关阅读:
    Filesystem Case-Sensitivity Mismatch
    内存分配
    单链表
    PHP校验日期格式是否合法
    Automatically populating $HTTP_RAW_POST_DATA is deprecated
    preg_match(): Compilation failed: character value in x{} or o{} is too large at offset 8
    CGI 和 FastCGI 协议的运行原理
    冒泡排序
    油猴子脚本-过滤百度广告
    查看chrome插件源码
  • 原文地址:https://www.cnblogs.com/MayGarden/p/1516813.html
Copyright © 2011-2022 走看看