【C++】单例模式:饿汉模式和懒汉模式

饿汉模式:提前创建一个静态的类对象,把所有能够创建对象的模块全部私有化,从外部需要创建类对象时只能返回事先创建好的唯一对象。就像一个特别饥饿的人,提前准备好食物,只要饿了,就可以立刻食用。

/*恶汉模式--单例模式*/
#include<iostream>
using namespace std;

class Singleton
{
public:
    static Singleton& GetInstance()
    {
        return _ps;
    }
private:
    Singleton(){};
    Singleton(const Singleton& s) = delete;
    Singleton& operator=(Singleton const&);
    static Singleton _ps ;
};

Singleton Singleton::_ps;

int main()
{
    cout << &Singleton::GetInstance() << endl;
    cout << &Singleton::GetInstance() << endl;
    return 0;
}

2.懒汉模式:也是把所有创建对象的模块私有化,当外部需要创建对象的时候,通过调用方法在类内部用new创建一个对象,如果对象已经存在则直接返回对象。不过需要考虑多线程情况,做加锁解锁处理。这种方法就像一个非常懒惰的人,只有在吃饭的时候才会洗碗。

*
 *单例模式---单例模式---懒汉模式式
 */
#include<mutex>
#include<thread>
#include <iostream>
using namespace std;

class Singleton
{
public:
    static Singleton* GetInstance()
    {
        if(nullptr == _ps){
            _mutex.lock();
            if(nullptr == _ps){
                _ps = new Singleton();
                cout << "test" << endl;
            }
            _mutex.unlock();
        }
        return _ps;
    }

public:
    class GC
    {
    public:
        ~GC(){
            if(nullptr != _ps){
                delete _ps;
                _ps = nullptr;
            }
        }
    };
private:
    Singleton(){};
    Singleton(const Singleton&);
    static Singleton* volatile  _ps;
    static mutex _mutex;
    static GC _gc;
};

Singleton* volatile Singleton::_ps = nullptr;
mutex Singleton::_mutex;
Singleton::GC _gc;

void Func()
{
    Singleton::GetInstance();
}

int main()
{
    thread t1(Func,10);
    thread t2(Func,10);
    t1.join();
    t2.join();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yulong__li/article/details/84714556
今日推荐