单例模式

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

#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

原文地址:https://www.cnblogs.com/icooper/p/4540523.html