码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 单例模式

时间:2014-08-22 14:25:28      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   ar   div   amp   log   line   

template<class Type>
class Singleton
{
protected:
    Singleton(){}
    ~Singleton(){}

    class EConstuct
    {
    public:
        EConstuct()
        {
            
        }
        ~EConstuct()
        {
            if(Singleton::object !=NULL)
                delete Singleton::object;

        }
    };


public:
    static Type *object;
    static EConstuct m_cons;

    static inline Type& instance()
    {
        if(object ==NULL)
        {
            printf("have construct \n");
            object = new Type();
        }
        return *object;
    }

};
template<class Type> Type* Singleton<Type>::object =NULL;

网上的一般是这种模式,今天发现了另外一种模式,比较新颖

template<class Type>
class Singleton2
{
public:
    Singleton2()
    {
        m_nReference++;
        if(m_object ==NULL)
        {
            m_object = new Type();
        }
    }
    virtual ~Singleton2()
    {
        m_nReference --;
        if(m_nReference==0)
        {
            printf("Deleted \n");
            delete m_object;
            m_object =NULL;
            breakPoint();
        }
    }


    Type *instance()
    {
        return m_object;
    }

    
    Type* operator ->() const
    {
        return m_object;
    }

    
private:

    static Type *m_object;
    static int m_nReference;
};

template<class Type>
Type* Singleton2<Type>::m_object =NULL;
template<class Type>
int Singleton2<Type>::m_nReference =0;

使用起来也方便

int main(int argc, char* argv[])
{
    Singleton2<Rte>  tmp ;
    tmp->data =10;

    printf("%d \n",tmp->data);
    Singleton2<Rte> temp;
    temp->data =40;
    printf("%d \n",tmp->data);
    temp.instance()->data =10;
    printf("%d \n",tmp->data);
    //printf("%f \n",Abc::instance().data);
    //Abc::instance().data =20;
    //printf("%f \n",Abc::instance().data);
    
    
    
    int gg;
    scanf("%d",&gg);
    
    return 0;
}

 

c++ 单例模式

标签:style   blog   color   使用   ar   div   amp   log   line   

原文地址:http://www.cnblogs.com/dragon2012/p/3929303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!