单例模式 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;
}

原文链接: https://www.cnblogs.com/zhuyf87/archive/2013/01/02/2842531.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    单例模式 c++实现

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74327

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:21
下一篇 2023年2月9日 下午4:21

相关推荐