zoukankan      html  css  js  c++  java
  • 单例模式(Singleton Pattern)

    Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点。这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程序在调用某一个类时,它是不会考虑这个类是否只能有一个实例等问题的,所以,这应该是类设计者的责任,而不是类使用者的责任。

    C#实现: 

    代码
        /// <summary>
        
    /// 简单实现
        
    /// </summary>
        public sealed class Singleton1
        {
            
    private static Singleton1 instance = null;
            Singleton1() { }
            
    public static Singleton1 Instance
            {
                
    get
                {
                    
    if (instance == null)
                    {
                        instance 
    = new Singleton1();
                    }
                    
    return instance;
                }
            }
        }

        
    /// <summary>
        
    /// 线程安全,双重锁定
        
    /// </summary>
        public sealed class Singleton2
        {
            
    private static Singleton2 instance = null;
            
    static readonly object padlock = new object();
            Singleton2() { }        
            
    public static Singleton2 Instance
            {
                get
                {
                    
    if (instance == null)
                    {
                        
    lock (padlock)
                        {
                            
    if (instance == null)
                            {
                                instance 
    = new Singleton();
                            }
                            
    return instance;
                        }
                    }
                }
            }
        }
  • 相关阅读:
    c++ this *this
    名称空间
    c++ 静态持续变量
    c++ 数组
    c++ 头文件
    实例化和具体化详解
    在linux下安装eclipse以及运行c++程序的安装步骤
    在centos (linux) 搭建 eclipse c++开发分环境
    Linux上使用Qt Creator进行C/C++开发
    使用Qt Creator 2.60编写C/C++程序
  • 原文地址:https://www.cnblogs.com/tqlin/p/1724799.html
Copyright © 2011-2022 走看看