zoukankan      html  css  js  c++  java
  • 个人理解的单例模式

    下面是个人理解的单例模式:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication6
    {
      public  sealed class Singleton
        {
          static Singleton instance;
          /// <summary>
          /// 为了避免实例不唯一,构造方法私有化
          /// </summary>
          private Singleton() { }
          public static Singleton Instance 
          {
              get 
              {
                  return instance == null ? new Singleton() : instance;
              }
          }
          public void dd(){
              Console.WriteLine("fdd");
              Console.ReadLine();
          }
         
        }
    }

    主方法调用如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication6
    {
        class Program
        {
            static void Main(string[] args)
            {
                Singleton.Instance.dd();
              
                
            }
        }
    }

    当然这有时候不能保证单例唯一,可以用lock方法来实现如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication6
    {
        public sealed class Singleton
        {
            static Singleton instance;
            static readonly object padlock = new object();
          
            public Singleton() { }
            public static Singleton Instance
            {
    
                get
                {
                    if (instance == null)
                    {
                        lock (padlock)
                        {
                            if (instance == null) 
                            {
                                instance=new Singleton() ;
                            }
                            
                        }
                       
                    }
                    return instance;
                }
            }
            public void dd()
            {
                Console.WriteLine("fdd");
                Console.ReadLine();
            }
    
        }
    }

    欢迎交流

  • 相关阅读:
    esp8266(3) Arduino通过ESP8266连接和获取网站源代码
    esp8266(2) 智能配置
    图像工程考试
    Arduino IDE for ESP8266 ()esp8266项目 WIFI攻击器
    esp8266(1) 手机+Arduino+esp8266通信
    esp8266(0) AT指令
    ROS ZED
    手机APP
    Arduino IDE for ESP8266教程(0)配置IDE
    Arduino 433 + 串口
  • 原文地址:https://www.cnblogs.com/huchaoheng/p/3774852.html
Copyright © 2011-2022 走看看