C++设计模式-singleton单例模式_new

 

class nocopyable
{
protected:
nocopyable(){};
virtual ~nocopyable(){};
nocopyable(const nocopyable&);
nocopyable& operator = (const nocopyable&);
};


template <typename T> class singleton : public nocopyable { public: static T* instance() { if (m_instance == NULL) { m_instance = new T(); } return m_instance; } static T * get_instance() { if (m_instance == NULL) { printf("m_instance is NULL\n"); } return m_instance; } static void destory_instance() { if (m_instance != NULL) { delete m_instance; m_instance = NULL; } } private: static T *m_instance; }; template<typename T> T* singleton<T>::m_instance = NULL;
class MySingletonClass : public singleton<MySingletonClass> {
public:
    MySingletonClass() {}
    ~MySingletonClass() {}

public:
    void DoPrint() {
        printf("This is MySingletonClass.\n");
    }
};

int main()
{
    MySingletonClass::instance();
    MySingletonClass::get_instance()->DoPrint();
    MySingletonClass::destory_instance();

    getchar();
    ;
}
上一篇:Vue.js学习使用心得(四)——组件


下一篇:微信小程序-参数传递与事件处理