三种单例模式实现

  1. 加锁的懒汉模式
class singleton
{
protected:
    singleton()
    {
    }
private:
    static singleton* p;
public:
    static pthread_mutex_t mutex;
    static singleton* initance();
};

pthread_mutex_t singleton::mutex= PTHREAD_MUTEX_INITIALIZER;;
singleton* singleton::p = NULL;
singleton* singleton::initance()
{
    if (p == NULL)
    {
        pthread_mutex_lock(&mutex);
        if (p == NULL)
            p = new singleton();
        pthread_mutex_unlock(&mutex);
    }
    return p;
}

  1. 内部静态变量实现的懒汉模式
class singleton
{
protected:
    singleton()
    {
    }
public:
    static singleton* initance();
};

singleton* singleton::initance()
{
    static singleton obj;
    return &obj;
}

  1. 初始化阶段实现的饿汉模式
class singleton
{
protected:
    singleton()
    {}
private:
    static singleton* p;
public:
    static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
    return p;
}

你可能感兴趣的:(c/c++/vc)