当前位置:网站首页>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


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

原网站

版权声明
本文为[Electric xuxiaojiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/199/202207161622326948.html