码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之 单例模式

时间:2015-07-30 18:35:49      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

 

#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;
}

 

设计模式之 单例模式

标签:

原文地址:http://www.cnblogs.com/foreverstars/p/4690079.html

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