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

    欢迎交流

  • 相关阅读:
    postgresql 配置文件优化
    postgresql 主从配置
    关于 pgsql 数据库json几个函数用法的效率测试
    linux 常用命令大全
    linux 禁ping本机方法
    inotify 心得
    安装PHP扩展
    centos 防火墙配置
    Java好的的工具类:JsonUtils
    Java好的的工具类:JSONResult
  • 原文地址:https://www.cnblogs.com/huchaoheng/p/3774852.html
Copyright © 2011-2022 走看看