1. 程式人生 > >Qt學習筆記-仿大佬讀取setting檔案(簡單工廠模式)

Qt學習筆記-仿大佬讀取setting檔案(簡單工廠模式)

檔案如下:

程式執行截圖如下:

程式碼如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QHostAddress>

class QSettings;

namespace Ui {
class Widget;
}


class ServerConfig:public QObject
{
    Q_OBJECT
public:
    ServerConfig();
    ~ServerConfig();

    static ServerConfig &instance();
    void loadConfig(QString config);

    QHostAddress m_address;
    quint16 m_port;
    quint16 m_threads;
    int m_maxConnections;

private:
    void parseConfig(const QString &config);

};

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QSettings>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ServerConfig &config=ServerConfig::instance();
    config.loadConfig("server.conf");
    qDebug()<<"address:"<<config.m_address;
    qDebug()<<"port:"<<config.m_port;
    qDebug()<<"threads:"<<config.m_threads;
    qDebug()<<"maxConnections:"<<config.m_maxConnections;
}

Widget::~Widget()
{
    delete ui;
}

ServerConfig::ServerConfig()
{

}

ServerConfig::~ServerConfig()
{

}

ServerConfig &ServerConfig::instance()
{
    static ServerConfig config;
    return config;
}

void ServerConfig::loadConfig(QString config)
{
    if(config.isEmpty()||!QFile::exists(config)){
        config="server.conf";
        if(!QFile::exists(config)){
            qDebug()<<"ServerConfig::loadConfig failed: no"<<config;
            return;
        }
    }
    parseConfig(config);
}

void ServerConfig::parseConfig(const QString &config)
{
    QSettings conf(config,QSettings::IniFormat);
    conf.beginGroup("server");
    QString strHost=conf.value("host","localhost").toString();
    if(!strHost.isEmpty()&&!m_address.setAddress(strHost)){
        m_address=QHostAddress::LocalHost;
    }
    m_port=conf.value("port",8088).toUInt();
    m_threads=conf.value("worker_threads",4).toUInt();
    m_maxConnections=conf.value("connections",200).toInt();
    conf.endGroup();
}

思路:這裡面ServerConfig並不是完全的解耦和。我們還是知道他內部的部分細節。

邏輯:讓ServerConfig生成一個instance,然後在loadConfig,這個邏輯十分簡單!