実現する方法
1.シングルトンを実現します。
クラスコンストラクター、コピーコンストラクター、および代入演算子をプライベートとして
定義します。シングルトンインターフェイスと一意のインスタンスポインターを静的として定義します。インスタンス化する必要はなく、クラス名に直接アクセスするだけです。
2.マルチスレッドのサポート:
ダブルチェックメソッドは、シングルトンを取得する機能で相互排他ロックを使用して、2つのスレッドがシングルトンクラスを同時にインスタンス化しないようにするために使用されます。
3.メモリリークを解決します。
シングルトンポインタを分解し、クラスを個別に記述し、このクラスのデストラクタを使用してシングルトンポインタを分解します。
コード
Instance.h
#ifndef INSTANCE_H
#define INSTANCE_H
#include <QObject>
#include <QMutex>
#include <QDebug>
class Instance : public QObject
{
Q_OBJECT
public:
static Instance *getInstance()
{
if(m_pInstance == NULL)
{
QMutexLocker mlocker(&m_mutex);
if(m_pInstance == NULL)
{
m_pInstance = new Instance();
}
}
return m_pInstance;
}
void debugStr();//对外接口,实现功能
QString m_str;//对外接口,实现功能
private:
explicit Instance(QObject *parent = 0);//构造函数
Instance(const Instance &,QObject *parent = 0): QObject(parent) {
}//拷贝构造函数
Instance& operator =(const Instance&){
return *this;}//赋值操作符重写
static Instance* m_pInstance;//定义单例指针
static QMutex m_mutex;//互斥锁
public:
class Garbo //专门用来析构m_pInstance指针的类
{
public:
~Garbo()
{
if(m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"m_pInstance 被析构";
}
}
};
static Garbo m_garbo;
};
#endif // INSTANCE_H
Instance.cpp
#include "instance.h"
#include <QDebug>
Instance* Instance::m_pInstance = NULL;
Instance::Garbo m_Garbo;
QMutex Instance::m_mutex;
void Instance::debugStr()
{
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"debugStr ";
}
Instance::Instance(QObject *parent) : QObject(parent)
{
m_str = "hello World!";
}
シングルトンを呼び出す
ヘッダーファイルが含まれ、シングルトンエントリを介して関数または変数を呼び出します。
#include“ instance.h”
Instance :: getInstance()-> debugStr();
Instance :: getInstance()-> m_str;