单例模式简介

  • 因为在设计或开发中,肯定会有这么一种情况,一个类只能有一个对象被创建,如果有多个对象的话,可能会导致状态的混乱和不一致。这种情况下,单例模式是最恰当的解决办法。它有很多种实现方式,各自的特性不相同,使用的情形也不相同。今天要实现的是常用的三种,分别是饿汉式、懒汉式和多线程式。
  • 通过单例模式, 可以做到:
  • 1.确保一个类只有一个实例被建立
  • 2.提供了一个对对象的全局访问指针
  • 3.在不影响单例类的客户端的情况下允许将来有多个实例
    例程:
#include <QCoreApplication>
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
once_flag g_flag;//定义标记

//std::call_once():c++11引入的函数,该函数的第二个参数是一个函数名a();
//call_once()功能是能够保证函数a()只被调用一次
//call_once()具备互斥量的能力,而效率上比互斥量消耗资源更少;
//call_once()需要与一个标记结合使用,这个标记std::once_flag; once_flag 是一个结构;
//call_once()就是通过这个标记来决定对应的函数a()是否执行,调用call_once()成功后,call_once就把这个标记设置为已调用状态

class  MyCAS{
private:
    MyCAS()//构造函数私有化,就不能通过MyCAS a 的形式构造对象了
    {

    }
private:
    static MyCAS *m_instance;//静态成员变量
    static std::mutex my_mutex;


public:
    static MyCAS *getInstance()
    {
        //提高效率:
        //1)如果   if(m_instance!=nullptr)条件成立,则肯定代表m_instance已经被new过了
        //2)如果   if(m_instance==nullptr),不代表m_instance一定没被new过

        if(m_instance==nullptr)//双重锁定为了提高效率,双重锁定只需在第一次构造对象时执行unique_lock,单重锁定每次都需要执行unique_lock
        {
            std::unique_lock<std::mutex> ulock(my_mutex);
            if(m_instance==nullptr)
            {
                m_instance=new MyCAS();
                static garbageCollection garbage_collection;
            }
        }
        return m_instance;
    }
    static MyCAS *getInstance2()
    {
        std::call_once(g_flag,createInstance);//两个线程同时执行到这里,其中一个线程要等另外一个线程执行完毕
        return m_instance;
    }

    class garbageCollection//类中套类,用于释放对象
    {
    public:
        ~garbageCollection()
        {
            if(MyCAS::m_instance)
            {
                delete MyCAS::m_instance;
                MyCAS::m_instance=nullptr;//指针要置空
            }
        }
    };
public:
    static void createInstance()//只执行一次
    {
        m_instance=new MyCAS();
        cout<<"createInstance is working! "<<endl;
        static garbageCollection garbage_collection;
    }
    void test()
    {
        cout<<"测试\n";
    }
};
//线程入口
void myThread(int num)
{
    cout<<"Thread "<<num<<"  is begining!\n";
    MyCAS *p_a=MyCAS::getInstance2();


    cout<<"Thread "<<num<<" is over!\n";
}
MyCAS  *MyCAS::m_instance=nullptr;
int main(int argc, char *argv[])
{
    //MyCAS *p_a=MyCAS::getInstance();
    //MyCAS *p_b=MyCAS::getInstance();//p_a与p_b指向同一对象

    thread thread1(myThread,1);
    thread thread2(myThread,2);
    thread1.join();
    thread2.join();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值