单例模式 c++实现

singleton.h:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

// Singleton 模式

#include "sync.h"
// #define NULL ((void *)0)

template <typename T>
class Singleton
{
private:
    Singleton() {};                              // ctor hidden
    Singleton (Singleton const&);                // copy ctor hidden
    Singleton & operator=( Singleton const&);    // assign op. hidden
    ~ Singleton ();                              // dtor hidden

    static T* instance_;

public:
    static T* Instance()
    {
        // double-check locking
        if (instance_ == NULL)
        {
            static CSync sync;
            sync.Lock();

            if (instance_ == NULL)
                instance_ = new T();

            sync.Unlock();

        }
        return instance_;
    }
};

template <typename T>
T* Singleton<T>::instance_ = NULL;

#endif // #ifndef _SINGLETON_H_

sync.h:

#ifndef _SYNC_
#define _SYNC_

#include <windows.h>

// critical_section
class CSync
{
private:
    void operator=(const CSync&);
    CSync(const CSync&);

    CRITICAL_SECTION critical_section_;

public:
    CSync() { InitializeCriticalSection(&critical_section_); }
    ~CSync() { DeleteCriticalSection(&critical_section_); }

    void Lock() { EnterCriticalSection(&critical_section_); }
    void Unlock() { LeaveCriticalSection(&critical_section_); }
};

#endif // #ifndef _SYNC_

test.cpp:

#include <iostream>
#include "singleton.h"

using namespace std;

class Mango
{
public:
    Mango() { cout << "Mango Constructor(). " << endl; }
};

int main()
{
    Mango* m1 = Singleton<Mango>::Instance();
    Mango* m2 = Singleton<Mango>::Instance();

    cout << m1 << "\n" << m2 << endl;

    return 0;
}

posted on 2013-01-02 22:42  zhuyf87  阅读(248)  评论(0编辑  收藏  举报

导航