⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 singleton.h

📁 C++ patterns设计模式
💻 H
字号:
////////////////////////////////////////////////////////////////////////////////
// Singleton模式
////////////////////////////////////////////////////////////////////////////////
// Author      : 黎达文 
// Description : 实现Singletone模式
//
// Version     : 1.0
//
// Depends     : none
//
// Start Date  : 2003年5月7日
//
// Change Log  : 
//2003年5月7日 by Darkay Li 
//-- Created
//2003年5月14日by Darkay Li 
//-- add other singleton -- StaticSingleton will create when first time access
//   and destroy when process end.
////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_SINGLETON
#define INCLUDED_SINGLETON

#if defined(HAS_PRAGMA_ONCE)
#pragma PRAGMA_ONCE_DECLARE
#endif

namespace stk
{
    //singleton
    //the user full control the create/destroy of instance
    template <typename T>
    class Singleton
    {
    public:
        //access singleton
        //@return<T> -- porinter of singleton
        static T* instance()
        {
            assert(m_instance);
            return m_instance;
        }

        //create instance by hand, with no arg
        static void newInstance()
        {
            if(!m_instance)
                m_instance = new T();
        }

        //create instance by hand, with one arg
        template<typename ARG>
        static void newInstance(ARG &arg)
        {
            if(!m_instance)
                m_instance = new T(arg);
        }

        //destroy instance by hand
        static void deleteInstance()
        {
            delete m_instance;
            m_instance = 0;
        }
    private:
        static T* m_instance;
    };

    //singleton
    //create when first time access
    //destroy just before process finish
    template<typename T>
    class StaticSingleton
    {
    public:
        static T * instance()
        {
            static T g_instance;
            return &g_instance;
        }
    };
}
//macro for help
#define INIT_SINGLETON(derive)     derive *stk::Singleton<derive>::m_instance = 0;
//define stk name
#define CTSingleton stk::Singleton
#define CTStaticSingleton stk::StaticSingleton

#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -