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

    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 
    ");
                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 
    ");
                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 
    ",tmp->data);
        Singleton2<Rte> temp;
        temp->data =40;
        printf("%d 
    ",tmp->data);
        temp.instance()->data =10;
        printf("%d 
    ",tmp->data);
        //printf("%f 
    ",Abc::instance().data);
        //Abc::instance().data =20;
        //printf("%f 
    ",Abc::instance().data);
        
        
        
        int gg;
        scanf("%d",&gg);
        
        return 0;
    }
  • 相关阅读:
    打印一个0到1之间的数的二进制表示
    bzoj-3223 文艺平衡树
    Linux下使用fstatfs/statfs查询系统相关信息
    Pku3664
    hdu-2544 最短路
    java同步包种ArrayBlockingQueue类的分析与理解
    【剑指offer】不用加减乘除做加法
    PA模块经常使用表
    网络编程
    // 插入排序 源代码
  • 原文地址:https://www.cnblogs.com/dragon2012/p/3929303.html
Copyright © 2011-2022 走看看