单例的实现
程序员文章站
2022-07-13 23:38:40
...
1 :test.h 声明
class SerialPort : public QObject
{
Q_OBJECT
public:
explicit SerialPort(QObject* parent = nullptr);
~SerialPort();
static int CreateInstance();
static void DestroyInstance();
//单例
static SerialPort* instance()
{
return m_instance;
}
private:
static SerialPort* m_instance;
};
2 :test.cpp 定义
//静态变量使用前必须初始化
SerialPort* SerialPort::m_instance = nullptr;
//创建单例
int SerialPort::CreateInstance()
{
SerialPort::m_instance = new SerialPort;
if (m_instance != nullptr)
{
return 0;
}
else
{
return -1;
}
}
//销毁单例
void SerialPort::DestroyInstance()
{
if (m_instance)
{
delete m_instance;
m_instance = NULL;
}
}
3 :main.cpp 使用
//实例化单例
m_attenSerialPort = SerialPort::instance();
//使用单例
QStringList portNameList = m_attenSerialPort->GetAvaliablePortNameList();
//摧毁单例
SerialPort::DestroyInstance();
上一篇: C#单例模式的三种写法