基本代码

懒汉模式

#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Singleton
{
private:
    static Singleton* instance;

    Singleton() {}

public:
    static Singleton* GetInstance()
    {
        if (instance == nullptr)
        {
            instance = new Singleton();
        }

        return instance;
    }
};
Singleton* Singleton::instance = nullptr;



int main()
{
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();

    if (s1 == s2)
    {
        cout << "两个对象是相同的" << endl;
    }


    system("pause");
    return 0;
}

多线程双重锁定版本

#include<iostream>
#include<string>
#include<vector>
#include<thread>
#include<mutex>

using namespace std;

#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Lock
{
private:
    mutex mut;
public:
    void lock() { mut.lock(); }
    void unlock() { mut.unlock(); }
};
class Singleton
{
private:

    static Singleton* instance;
    static Lock* locker;

    Singleton() {}

public:
    static Singleton* GetInstance()
    {
        if (instance == nullptr)
        {
            locker->lock();
            if(instance == nullptr)
                instance = new Singleton();
            locker->unlock();
        }

        return instance;
    }
};
Singleton* Singleton::instance = nullptr;
Lock* Singleton::locker = new Lock();



int main()
{
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();

    if (s1 == s2)
    {
        cout << "两个对象是相同的" << endl;
    }


    system("pause");
    return 0;
}

饿汉模式

#include <iostream>

using namespace std;

class Singleton {
public:
    ~Singleton();
    //提供单例对象访问
    static Singleton* getInstance();
    void doSomething();
protected:
    //构造函数声明为 保护方法
    Singleton();
    //单例对象指针
    static Singleton* theSingleton;
};

//提供单例类对象访问
Singleton* Singleton::getInstance() {
    return theSingleton;
}

void Singleton::doSomething()
{
    cout << "饿懒汉模式" << "\n" << "单例模式" << endl;
}

Singleton::Singleton()
{
}
Singleton::~Singleton()
{}

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

int main()
{
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();

    if (s1 == s2)
    {
        cout << "两个对象是相同的" << endl;
    }

    system("pause");
    return 0;
}

Meyers Singleton(目前最推荐的C++单例写法)

#include <iostream>

using namespace std;

class Singleton
{
public:
    static Singleton& Instance()
    {
        static Singleton theSingleton;
        return theSingleton;
    }
    void doSomeThong();
private:
    Singleton();
    ~Singleton();
};

Singleton::Singleton()
{
}

Singleton::~Singleton()
{
}
void Singleton::doSomeThong()
{
    cout << "单例类" << endl;
    cout << "C++最推荐的单例类写法" << endl;
}

int main()
{
    Singleton::Instance().doSomeThong();

    system("pause");
    return 0;
}
12-16 04:58