Stdlib log模块类图

\"\"

 

Stdlib 模板单例源码

这里只提炼单例模板的使用,所以不附上全部源码。

Singleton.h:

#ifndef __SINGLETON_H

#define __SINGLETON_H

 * Singleton design pattern; only one instance is allowed.

template <class T> class Singleton

  public:

    /**

     * Constructor

     * @param instance New instance of T.

     */

    Singleton<T>(T *obj)

        instance = obj;

    /** One and only instance. */

    static T *instance;

/* Initialize the static member obj. */

template <class T> T* Singleton<T>::instance = 0;

#endif /* __SINGLETON_H */

Log.h

class Log : public Singleton<Log>

  public:

    /**

     * Constructor.

     */

    Log();

    /**

     * Destructor

     */

    virtual ~Log();

Log.c

#include \"Log.h\"

#include \"String.h\"

Log::Log() : Singleton<Log>(this)

    setMinimumLogLevel(Debug);

Log::~Log()

个人修改后的模板单例代码

Csingleton.h

#ifndef CSINGLETON

#define CSINGLETON

template <class T>

class CSingleton

public:

    CSingleton<T>()

    static T* getInstance()

            if(m_instance == 0)

            {

                m_instance = new T();

            }

            return m_instance;

private:

    static T* m_instance;

template <class T> T* CSingleton<T>::m_instance = 0;

#endif // CSINGLETON

Clog.h

#ifndef CLOG_H

#define CLOG_H

#include \"csingleton.h\"

class CLog:public CSingleton<CLog>

public:

    CLog();

    virtual ~CLog();

#endif // CLOG_H

Clog.cpp

#include \"clog.h\"

CLog::CLog() : CSingleton<CLog>()

CLog::~CLog()

Main.cpp

#include <iostream>

#include \"clog.h\"

using namespace std;

int main()

    cout << \"Hello World!\" << endl;

    CLog *clog1 = CLog::getInstance();

    CLog *clog2 = CLog::getInstance();

    cout<<clog1<<endl;

    cout<<clog2<<endl;

    return 0;

收藏 打印