创建型模式--单例模式

懒汉模式

#include <iostream>
#include <pthread.h>
using namespace std;

class Singleton 
{
public:
    static Singleton *getInstance();

private:
    Singleton();
    ~Singleton();
    static Singleton *m_pInstance;
    static pthread_mutex_t mutex;
};

Singleton *Singleton::m_pInstance = NULL;
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;

Singleton::Singleton()
{
    pthread_mutex_init(&mutex, NULL);
}

Singleton *Singleton::getInstance()
{
    if (m_pInstance == NULL) 
    {
        pthread_mutex_lock(&mutex);
        if (m_pInstance == NULL)
        {
            m_pInstance = new Singleton();
        }
        pthread_mutex_unlock(&mutex);
    }
    return m_pInstance;
}

Singleton::~Singleton()
{
    if (m_pInstance != NULL)
    {
        delete m_pInstance;
    }
}

int main()
{
    Singleton *instance1 = Singleton::getInstance();
    Singleton *instance2 = Singleton::getInstance();

    if (instance1 == instance2)
    {
        cout << "instance1 == instance2" << endl;
    }
    return 0;
}

饿汉模式

#include <iostream>
using namespace std;

class Singleton
{
public:
    static Singleton *getInstance();

private:
    Singleton() {}
    ~Singleton();
    static Singleton *m_pInstance;
};

Singleton* Singleton::m_pInstance = new Singleton();

Singleton* Singleton::getInstance()
{
    return m_pInstance;
}

int main()
{
    Singleton *instance1 = Singleton::getInstance();
    Singleton *instance2 = Singleton::getInstance();

    if (instance1 == instance2)
    {
        cout << "instance1 == instance2" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/teffi/article/details/81024826