实现方式
1、实现单例
把类的构造函数、拷贝构造函数、赋值操作符定义为private的;
把获取单例的接口和唯一的实例指针定义为static的,不需要实例化,直接通过类名即可访问。
2、支持多线程
采用双重校验法,在获取单例的函数中使用互斥锁,确保不会出现两个线程同时new出这个单例类的实例化。
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
{
public:
~Garbo()
{
if(m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"m_pInstance 被析构";
}
}
};
static Garbo m_garbo;
};
#endif
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)