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

    欢迎交流

  • 相关阅读:
    七层协议&网络配置
    解决跨域问题
    拖拽 ‘vue-grid-layout’ 插件了解下
    详解vuex
    在腾讯出差的日子
    对象的解构赋值应用
    MQTT项目请求设置
    五分钟搞定Go.js
    Chrome使用video无法正常播放MP4视频的解决方案
    微信小程序地图开发总结
  • 原文地址:https://www.cnblogs.com/huchaoheng/p/3774852.html
Copyright © 2011-2022 走看看