单例模式

2020-05-13  本文已影响0人  Coding破耳

保证一个类仅有一个实例,并提供一个访问它但全局访问点。通常我们可以让一个全局变量使得一个对象被访问,但它不能防止你实例化多个对象。一个最好但办法就是,让类自身负责保存它但唯一实例。这个类可以保证没有其它实例可以被创建,并且它可以提供一个访问该实例的方法。

private的构造方法,确保无法在外部创建实例。
static 静态对象

https://blog.csdn.net/qq_29542611/article/details/79301595
https://blog.csdn.net/linlin003/article/details/79012416

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;
mutex mu;//线程互斥对象
class Singleton_Hungry
{
private:
    Singleton_Hungry()
    {
        cout << "我是饿汉式,在程序加载时,我就已经存在了。" << endl;
    }
    static Singleton_Hungry* singleton;
public:
    static Singleton_Hungry* getInstace()
    {
        return singleton;
    }
    
};
//静态属性类外初始化
Singleton_Hungry* Singleton_Hungry::singleton = new Singleton_Hungry;

class Singleton_Lazy
{
private:
    Singleton_Lazy()
    {
        cout << "我是懒汉式,在别人需要我的时候,我才现身。" << endl;
    }
    static Singleton_Lazy* singleton;
public:
    static Singleton_Lazy* getInstance()
    {
        
        if (NULL == singleton)
        {
            
            mu.lock();//打开锁
            if (NULL == singleton)
            {
                singleton = new Singleton_Lazy;
            }
            mu.unlock();//关闭锁
        }
        return singleton;
    }
};
Singleton_Lazy* Singleton_Lazy::singleton = NULL;
void thread01()
{
    for (int i = 0; i < 5; i++)
    {
        cout << "thread01 working...." << endl;
        Singleton_Lazy *lazy1 = Singleton_Lazy::getInstance();
        cout << "thread01创建单例lazy1地址:" << lazy1 << endl;
    }
}
void thread02()
{
    for (int i = 0; i < 5; i++)
    {
        cout << "thread02 working...." << endl;
        Singleton_Lazy *lazy2 = Singleton_Lazy::getInstance();
        cout << "thread02创建单例lazy2地址:" << lazy2 << endl;
    }
}

int main(int argc, char *argv[])
{
    thread thread1(thread01);
    thread thread2(thread01);
    thread1.detach();
    thread2.detach();
    for (int i = 0; i < 5; i++)
    {
        cout << "Main thread working..." << endl;
        Singleton_Lazy *main = Singleton_Lazy::getInstance();
        cout << "Main 创建单例lazy地址:" << main << endl;
    }
    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读