当前位置: 首页 > article >正文

单例模式的学习

示例:

#ifndef TEST_H
#define TEST_H


class test
{
public:
    static test * GetINSTANCE();
    void print();
private:
    test();
};

#endif // TEST_H
#include "test.h"
#include <QMutex>
#include <QDebug>
test::test()
{

}

test *test::GetINSTANCE()
{
    static test * inst = nullptr;
    static QMutex mutex;
    mutex.lock();
    if(!inst)
    {
        inst = new test;
    }
    mutex.unlock();
    return inst;
}

void test::print()
{
    static int m = 0;
    m++;
    qDebug()<<__FILE__<<"["<<__LINE__<<"]"<< m;
}
    test::GetINSTANCE()->print();
    test::GetINSTANCE()->print();
    test::GetINSTANCE()->print();

..\try\test.cpp [ 26 ] 1

..\try\test.cpp [ 26 ] 2

..\try\test.cpp [ 26 ] 3

使用类模板进行简单的优化,使代码扩展性更好一些:

#ifndef TEST_H
#define TEST_H

#include <QMutex>

template<typename T>
class Singleton
{
public:
    static T * GetINSTANCE()
    {
        static T * inst = nullptr;
        static QMutex mutex;
        mutex.lock();
        if(!inst)
        {
            inst = new T();
        }
        mutex.unlock();
        return inst;
    }
protected:
    Singleton() = default;
};


class test:public Singleton<test>
{
    friend class Singleton<test>;
public:
    void print();
private:
    test() = default;
};
#endif // TEST_H
#include "test.h"
#include <QDebug>

void test::print()
{
    static int m = 0;
    m++;
    qDebug()<<__FILE__<<"["<<__LINE__<<"]"<< m;
}
    test::GetINSTANCE()->print();
    test::GetINSTANCE()->print();
    test::GetINSTANCE()->print();

..\try\test.cpp [ 11 ] 1

..\try\test.cpp [ 11 ] 2

..\try\test.cpp [ 11 ] 3


http://www.kler.cn/a/297711.html

相关文章:

  • 【sensor】激光雷达的特性与参数详解(七)Velodyne VLP-16 激光雷达的关键参数举例
  • C++基础(7.Stack_Quene_List)
  • rustDesk远程软件,强的可怕
  • c++修炼之路之C++11
  • 1.单例模式
  • 4.第二阶段x86游戏实战2-CE加强修改移动速度(浮点数存放方式与转换)
  • STL-List常用接口
  • 可重复读级别下避免幻读问题的方法
  • Android 系统源码项目加载预编好的so库
  • 通信工程学习:什么是ATM异步转移模式
  • 【机器人工具箱Robotics Toolbox开发笔记(一)】Matlab机器人工具箱简介
  • CCF-CSP认证考试准备第十一天
  • Web 原生组件化方案:Web Components
  • 【C++初阶】:C++入门,引用概念及其性质
  • 《A Few Useful Things to Know about Machine Learning》论文导读
  • 判断PDF与图片是否可以预览
  • 什么是生成式 AI?
  • 嵌入式软件--51单片机 DAY 3
  • sheng的学习笔记-AI-话题模型(topic model),LDA模型,Unigram Model,pLSA Model
  • 安卓链接正常显示,ios#符被转义%23导致链接访问404