讨论/《深入浅出设计模式》 - 单例模式 Singleton/
《深入浅出设计模式》 - 单例模式 Singleton

c++实现:
静态变量实现线程安全饿汉式:

class Singleton{
private:
    Singleton(){}
    Singleton(const Singleton& temp){}
    Singleton& operator=(const Singleton& temp){}
public:
    static Singleton& getInstence(){ 
        static Singleton instence;
        return instence;
    }
};

加锁实现线程安全饿汉式:

class Singleton{
private:
    static pthread_mutex_t mutex;
    static Singleton * instence;
    Singleton(){
        pthread_mutex_init(&mutex, NULL); 
    }
    Singleton(const Singleton& tmp){}
    Singleton& operator=(const Singleton& tmp){}
public:
    static Singleton* getInstence(){
        if(instence == NULL) {
            pthread_mutex_lock(&mutex);
            if(instence == NULL){            
                instence = new Singleton();            
            }
            pthread_mutex_unlock(&mutex);
        }
        return instence;
    }
};
Singleton* Singleton::instence = NULL;
pthread_mutex_t Singleton::mutex;
展开全部 6 讨论