zoukankan      html  css  js  c++  java
  • 单例模式

      分享一个我在工作中用到的单例类,也欢迎大家留言批评指正。

    #ifndef _SINGLETON_H_
    #define _SINGLETON_H_
    
    //单件类
    template <class T>
    class  CSingleton
    {
    public:
        static T* Instance(bool bAutoClean = true)
        {
            if(NULL == _instance)
            {
                _instance = new T;
    
                if (bAutoClean)
                {
                    static clean cleaner;
                }
            }
    
            return _instance;
        }
    
        static void DeleteSingleton()
        {
            if(NULL != _instance)
            {
                delete _instance;
                _instance = NULL;
            }
        }
    
    protected:
        CSingleton(){}          //单件类不能被实例化,所以为保护成员
    private:
        static T* _instance; 
    
        class clean
        {
        public:
            clean(){}
            ~clean()
            {
                if(NULL != _instance)
                {
                    delete _instance;
                    _instance = NULL;
                }
            }
        };
    };
    
    template <class T>  T* CSingleton<T>::_instance = 0;
    
    #endif

    注:单例模式是一种非常常用的设计模式,在网上搜了很多个版本,发现都有一些缺陷,所以决定自己重写一个单例类。

    使用了C++模板技术、嵌套类,不懂的同学自己去翻翻书吧!此单例类包含了自动清除内存功能,看代码中的static clean cleaner;

    转载请指明出处:http://www.cnblogs.com/icooper/p/4540523.html

  • 相关阅读:
    文件路径选择中的三态逻辑
    .net版本号
    使用MSBuild编译vs多个解决方案
    CEF截图
    使用SharpZIpLib写的压缩解压操作类
    软件试用期设置
    list转datatable
    excel 导入
    网站登录简单验证码
    UEditor编辑器
  • 原文地址:https://www.cnblogs.com/icooper/p/4540523.html
Copyright © 2011-2022 走看看