跳转到帖子
登录关注  
墨香年少

Qt下的单例模式

已推荐帖子

static MyClass* MyClass::Instance()
{
    static QMutex mutex;
    static QScopedPointer<MyClass> inst;
    if (Q_UNLIKELY(!inst)) {
        mutex.lock();
        if (!inst) {
            inst.reset(new MyClass);
        }
        mutex.unlock();
    }
    return inst.data();
}

比如单例模式下的socket

.h

#ifndef SOCKET_H
#define SOCKET_H

#include <QObject>
#include <QTcpSocket>

class Socket : public QObject
{
    Q_OBJECT
public:
    static Socket* Instance();
    QString getErr();
    bool isOpen();
    bool send(QString header,QString msg);
private:
    QString err = "";
    QTcpSocket* client;
    explicit Socket(QObject *parent = nullptr);
signals:

};

#endif // SOCKET_H

.cpp

#include "socket.h"

#include <QDataStream>
#include <QMutex>
#include <QSettings>
#include <QDebug>

Socket* Socket::Instance()
{
    static QMutex mutex;
    static QScopedPointer<Socket> inst;
    if (Q_UNLIKELY(!inst)) {
        mutex.lock();
        if (!inst) {
            inst.reset(new Socket);
        }
        mutex.unlock();
    }
    return inst.data();
}

Socket::Socket(QObject *parent) : QObject(parent)
{
    QSettings* regedit  = new QSettings("HKEY_CURRENT_USER\\SOFTWARE\\AdoDisk", QSettings::NativeFormat);
    QString server_ip   = regedit->value("socket_server").toString();
    QString server_port = regedit->value("socket_port").toString();

    if("" != server_ip && "" != server_port)
    {
        client = new QTcpSocket(this);
        if(!client->isOpen())
        {
            client->connectToHost(server_ip,server_port.toInt());
            if(client->waitForConnected())
            {
                qDebug() << "socket connect success";
                err = "";

            }
            else
            {
                err = QString("socket connect failed, err:%1.").arg(client->errorString());
                qDebug() << err; //"socket connect failed, err:Connection refused."
            }
        }
    }
}

QString Socket::getErr()
{
    return err;
}

bool Socket::isOpen()
{
    return client->isOpen();
}

bool Socket::send(QString _header, QString msg)
{
    if(!client)
    {
        return false;
    }
    if(!client->isOpen())
    {
        return false;
    }
    QDataStream socketStream(client);
    socketStream.setVersion(QDataStream::Qt_5_12);

    QByteArray header;
    header.prepend(_header.toUtf8());
    header.resize(128);

    QByteArray byteArray = msg.toUtf8();
    byteArray.prepend(header);

    socketStream << byteArray;
    byteArray.clear();

    return true;
}

调用:

Socket::Instance()->isOpen()

 


目之所及,皆是回忆,心之所想,皆是过往

分享这篇帖子


链接帖子
分享到其他站点

创建帐户或登录来提出意见

你需要成为会员才能提出意见

创建帐户

注册成为会员。只要几个简单步骤!

注册帐户

登录

已有帐户? 请登录。

现在登录
登录关注  

×
×
  • 创建新的...

重要信息

注册必须使用2-8个中文汉字作为账号