当前位置:网站首页>Singleton mode in QT: implement a singleton interface class
Singleton mode in QT: implement a singleton interface class
2022-07-18 19:46:00 【Electric xuxiaojiang】
List of articles
Preface
This article mainly describes the use of lazy locking to achieve a single example , The example in this article changes an interface class to a singleton class , And get multiple instances of this class in the main interface for testing , The result shows that only one instance is generated , This simple example is a summary of my learning and understanding of the singleton pattern . If there is any mistake in the text , Welcome criticism .
Tips : The following is the main body of this article , The following cases can be used for reference
One 、 What is singleton mode
The singleton pattern , It is a common software design pattern of creation type . The class created by the method of singleton pattern ensures that there is only one instance of this class , And provide a global access point to access it .
Two 、 Advantages, disadvantages and usage scenarios of singleton mode
You can read this article , The summary is quite comprehensive : Advantages, disadvantages and application scenarios of singleton mode
3、 ... and 、Qt The creation of singleton class in
1.config.h
#ifndef CONFIG_H
#define CONFIG_H
#include <QWidget>
#include <QMutex>
#include <QMutexLocker>
#include <QDebug>
namespace Ui {
class Config;
}
class Config : public QWidget
{
Q_OBJECT
public:
//explicit Config(QWidget *parent = nullptr);
~Config();
// Provide a public static interface , Get an instance of this class
static Config* getInstance();
private:
Ui::Config *ui;
// Constructor privatization , Prevent the outside world from creating instances of this class through construction
explicit Config(QWidget *parent = nullptr);
// Add a private static pointer variable to point to the unique instance of this class
static Config* instance;
};
#endif // CONFIG_H
2.config.cpp
#include "config.h"
#include "ui_config.h"
// Class initialization
Config* Config::instance = nullptr;
QMutex mutex;
Config::Config(QWidget *parent) :
QWidget(parent),
ui(new Ui::Config)
{
ui->setupUi(this);
this->setAttribute(Qt::WA_QuitOnClose,false); // The setting closes when the main window closes
}
Config::~Config()
{
qDebug()<<"~ Config";
delete ui;
}
// Lazy implementation of locking
Config* Config::getInstance()
{
// Race conditions may be triggered when multithreading obtains a singleton
static QMutex mutex;
if(!instance)
{
QMutexLocker locker(&mutex); // Lock , Solve the problem of thread safety
if(!instance)
{
qDebug()<<"new Config";
instance = new Config; // Pay attention to memory leakage
}
}
return instance;
}
Four 、 The use of singleton classes / test
1.widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "config.h" // If you include a singleton class header file, you can get an instance through the interface
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pb_config_clicked();
void on_pb_config_1_clicked();
void on_pb_config_2_clicked();
private:
Ui::Widget *ui;
//Config* instance = nullptr;
};
#endif // WIDGET_H
2.widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// You can get the instance of the singleton class when the main interface is constructed , Coordinate destruct
//instance = Config::getInstance();
}
Widget::~Widget()
{
// The singleton class instance in the destruct delete, Prevent memory leaks
//if(instance)
//{
// delete instance;
//}
delete ui;
}
void Widget::on_pb_config_clicked()
{
// Display the instance interface created during construction
//instance->show();
}
// Get instance of class twice , But only once the constructor of the class is called , Indicates that only a unique instance has been generated
void Widget::on_pb_config_1_clicked()
{
Config* instance_1 = Config::getInstance();
instance_1->show();
}
void Widget::on_pb_config_2_clicked()
{
Config* instance_2 = Config::getInstance();
instance_2->show();
}
3. Output results
Click two buttons on the interface respectively , Only one interface will appear , Check the printout only once "new Config", Click any button to display the interface , Clicking another button has no effect .
summary
In fact, at present, I still don't know much about design patterns , So we still need to strengthen learning . There are many software design patterns , There is no need to write design patterns for design patterns , It mainly depends on whether the problems solved by those design patterns are the problems you encounter ? Combined with the actual project , Choose what you need .
The singleton design pattern described in this article , As the reference article says :
You need to have one and only one object of a type in system
You only use singleton when you need the global variables of a class in which only one instance exists in the system .
If single example is used , What should it look like ?
The smaller the better. , The simpler, the better , Thread safety , No memory leaks .
hello:
Learning together , Common progress , If there are related questions , You can leave a message in the comment area for discussion .
Reference article :
C++ Summary and analysis of single case model
c++ Design patterns ( One ) The singleton pattern
边栏推荐
- Custom JSP tag
- Unity 视频控制暂停播放以及滑动条拖拽(笔记)
- Machine learning: cross entropy from theory to code
- Towards verifiable AI: five challenges of formal methods
- Dark horse programmer - software testing -14 stage 3- function testing -66-77 Zen introduction, product manager uses Zen, super administrator uses Zen, super administrator modifies security strategy,
- 六、关联查询优化、七 排序分组优化、八截取查询分析
- airtest+poco多脚本、多设备批处理运行测试用例自动生成测试报告
- VIVADO 以太网接口(SGMII转GMII接口)
- 北京现代20周年:精简产品布局,力争2025年实现52万辆
- Tool use -editor MD editor
猜你喜欢

Dark horse programmer - software testing -14 stage 3- function testing -66-77 Zen introduction, product manager uses Zen, super administrator uses Zen, super administrator modifies security strategy,

Machine learning: cross entropy from theory to code

How to recover if the win11 mouse can't move? Win11 method of recovering from mouse immobility

Google Earth engine (GEE) -- the problem of over limit timeout extraction (applicable to besteffort)

「 每日一练,快乐水题 」1252. 奇数值单元格的数目

满电出行王颖:用数据安全护航智慧出行

在四线城市生活,拿一线城市工资,是种怎样的体验?

How does win11 remove the network speed limit? Win11 method of lifting network speed limit

内存函数的介绍及模拟实现

Window10 远程桌面连接提示:“无法定位程序输入点:_CxxFrameHandler4 于动态链接库”错误的解决方法
随机推荐
Machine learning: cross entropy from theory to code
Aike AI frontier promotion (7.16)
股权分配协议 (1)
Format output text in CAD
Custom JSP tag
Win32 process lock process asynchronism process mutex CreateMutex OpenMutex WaitForSingleObject releasemutex
3.2. Alexnet model
六、關聯查詢優化、七 排序分組優化、八截取查詢分析
MQ简单介绍
Equity distribution agreement (1)
Is personalized recommendation really a "demon"?
go语言整数二分模板
黑马程序员-软件测试-14阶段3-功能测试-66-77禅道介绍,产品经理使用禅道,超级管理员使用禅道,超级管理员修改安全策略公司部门员工信息项目经理创建项目设置团队关联需求添加任务,产品经理需求评审,
swift中struct & class &闭包封装
JMeter 21 day clock in day07
[tools] visual studio keymap
渐隐渐现1920-500(7)
Unity 视频控制暂停播放以及滑动条拖拽(笔记)
3.3. VGG_ model
电影知识图谱和基于模板的问答系统构建