c++ 饿汉式、懒汉式 单例模式

饿汉式

class SingleInstance{
     
private:
    SingleInstance(){
     }
    static SingleInstance* pInstance;
public:
	static SingleInstance *getInstance(){
     
		return pInstance;
	}
};
SingleInstance* SingleInstance::pInstance = new SingleInstance;

懒汉式

class SingleInstance{
     
private:
    SingleInstance(){
     
        pthread_mutex_init(&mutex);
    }
private:
    static SingleInstance* pInstance;
public:
    static pthread_mutex_t mutex;
    static SingleInstance* getInstance(){
     
        if (pInstance == NULL){
     
            pthread_mutex_lock(&mutex);
            if (pInstance == NULL)
                pInstance = new SingleInstance();
            pthread_mutex_unlock(&mutex);
        }
        return pInstance;
    }
};
pthread_mutex_t SingleInstance::mutex;
SingleInstance* SingleInstance::pInstance = NULL;

你可能感兴趣的:(c++ 饿汉式、懒汉式 单例模式)