Skip to content

Latest commit

 

History

History
50 lines (43 loc) · 1.07 KB

单例模板类.md

File metadata and controls

50 lines (43 loc) · 1.07 KB

概 述

之前有讨论过单例模式的实现(C++ 单例模式),然而在实际开发中,将多个类做成单例,需要对每一个进行改造,造成重复劳动。我们可以使用模板类来避免重复劳动。

实 现

使用 Meyers' Singleton,可以很快的实现单例模板类,如下:

// Singleton.h
template<typename ClassType>
class Singleton
{
public:
    static ClassType * instance();

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton() = default;
    ~Singleton() = default;
};

template<typename ClassType>
ClassType * Singleton<ClassType>::instance()
{
    static ClassType s_singleton;
    return &s_singleton;
}

使 用

有了单例模板类,使用起来就很方便

// Log.h
#include "Singleton.h" //引入单例模板类

class Log {
public:
    void init();
    //...
}

using g_LogMgr = Singleton<Log>; //定义日志单例模块别名

// main.cpp
int main
{
    g_LogMgr::instance()->init(); //使用
    //...
    return 0;
}