zoukankan      html  css  js  c++  java
  • 设计模式:单例模式

    单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    懒汉式:

    namespace SingletonDesign
    {
        public 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;
            }
        }
    }
    View Code

    测试代码:

                for(int i=0;i<100;i++)
                {
                    Task.Run(() => {
                        Singleton s = Singleton.GetInstance();
                        Console.WriteLine(s.GetHashCode());
                    });
                }
    View Code

    饿汉式:

    namespace SingletonDesign
    {
        public sealed class Singleton
        {
            private static readonly Singleton instance=new Singleton();
            private Singleton() { }
            public static Singleton GetInstance()
            {
                return instance;
            }
        }
    }
    View Code
  • 相关阅读:
    Git+GitHub+SaltStack
    系统运维
    Linux之Ubuntu
    TCP/IP 必知必会的十个问题
    Github常见操作和常见错误!
    Git钩子:自定义你的工作流
    Spring 梳理
    Spring 梳理
    Spring 梳理
    Spring boot 官网学习笔记
  • 原文地址:https://www.cnblogs.com/uptothesky/p/5283815.html
Copyright © 2011-2022 走看看