设计模式之单例模式

C++实现单例模式

 singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include <pthread.h>

class Singleton
{
public:
    static Singleton* getInstance()
    {
        if(nullptr == instance)
        {
            pthread_mutex_lock(&mutex);
            if(nullptr == instance) instance = new Singleton();
            pthread_mutex_unlock(&mutex);
        }
        return instance;
    }
private:
    Singleton(){}
    Singleton(const Singleton &);
    Singleton(const Singleton &&);
    static Singleton *instance;
    static pthread_mutex_t mutex;
};

#endif

 

 singleton.cpp

#include "singleton.h"

pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton* Singleton::instance = nullptr;

编译:

g++ -std=c++11 -c singleton.cpp -lpthread


刚刚学习单例模式,不足之处希望大家多多指教

posted @ 2017-02-04 21:18  txlstars  阅读(130)  评论(0编辑  收藏  举报