设计模式之 单例模式

 

#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;

/*
template<class T,  class StaticMutex>
class SingleInstance
{
protected:
    SingleInstance(void){}
    virtual ~SingleInstance(void){}
    T* CreateInstance(void)
    {
        if(!pIns_)
        {
            mutex_.lock();
            if(!pIns_)
            {
                pIns_ = new T();
            }
            mutex_.unlock();
        }
        return pIns_;
    }
    void destoryInstance()
    {
        if(pIns_)
        {
            delete pIns_;
            pIns_ = NULL;
        }
    }
private:
    static T *pIns_;
    StaticMutex mutex_;
};
*/

template<class T>
class SingleInstance
{
protected:
    SingleInstance(void){}
    virtual ~SingleInstance(void){}
    static T* createInstance(void)
    {
        if(!pIns_)
        {
            pIns_ = new T();
        }
        return pIns_;
    }
    void destoryInstance()
    {
        if(pIns_)
        {
            delete pIns_;
            pIns_ = NULL;
        }
    }
private:
    static T *pIns_;
};

template<typename T>
T* SingleInstance<T>::pIns_ = NULL;

class Factory: public SingleInstance<Factory>
{
public:
    Factory(void){}
    ~Factory(void){ destoryInstance(); }
    static Factory* instance(void){ return createInstance(); }

    void show(){ cout<<"create a factory instance ok"<<endl; }
};

int main()
{
    Factory::instance()->show();
    return 0;
}

 

posted on 2015-07-30 17:48  霏霏暮雨  阅读(130)  评论(0编辑  收藏  举报

导航