zoukankan      html  css  js  c++  java
  • C# 设计模式(1)单例模式

    单例模式:

    1. 程序只需要这个对象实列化一次.

    2. 不能解决多线程并发问题

    3. 主要应用于 数据库连接池、线程池、流水号生成器、配置文件读取、IOC容器实列

    实现方法一(懒汉式)

        class Program
        {
            static void Main(string[] args)
            {
                for (int i = 0; i < 5; i++)
                {
                    Task.Run(() =>
                    {
                        Console.WriteLine($"HashCode is {Singleton.GetInstance().GetHashCode()}");
                    });
                }
    
                Console.ReadLine();
            }
        }
    
        public class Singleton
        {
            private static Singleton _singleton;
            private static readonly object _lock = new object();
            private Singleton()
            {
                
            }
    
            public static Singleton GetInstance()
            {
                if(_singleton==null)
                {
                    lock (_lock)
                    {
                        if (_singleton == null)
                            _singleton = new Singleton();
                    }
                }
                return _singleton;
            }
        }
    

     实现方法二:(饿汉式)

        class Program
        {
            static void Main(string[] args)
            {
                for (int i = 0; i < 5; i++)
                {
                    Task.Run(() =>
                    {
                        Console.WriteLine($"HashCode is {SingletonSecond.GetInstance().GetHashCode()}");
                    });
                }
                Console.ReadLine();
            }
        }
    
        public class SingletonSecond
        {
            private static readonly SingletonSecond _singletonSecond;
            private SingletonSecond()
            {
    
            }
    
            static SingletonSecond()
            {
               _singletonSecond =  new SingletonSecond();
            }
    
            public static SingletonSecond GetInstance()
            {
                return _singletonSecond;
            }
        }
    

  • 相关阅读:
    vs.net2003里添加邮件发件人身份验证
    Linux下用PYTHON查找同名进程
    修改机器名后要修改IIS匿名访问用户
    [C#]使用MYSQL数据库
    JIRA OutOfMemoryErrors
    获取linux下当机堆栈
    python调用pipe
    [探讨]一次性工具软件
    GGSN
    三层交换机的作用
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14060090.html
Copyright © 2011-2022 走看看