深入Qt–单例模式
4年前开始进入C++编程时看到好多前辈们在写单例模式的时候,在公司写的程序也是一样。都是在类中实现单例。下面要介绍的是基于模板编程实现的单例模式。如果对单例模式及模板编程不熟的发烧友,需要自行学习。
实现比较简单:
#ifndef SINGLETON_H
#define SINGLETON_H
#include <memory>
template<class T, class X, int N>
T& GetInstanceX()
{
static T v;
return v;
}
template<class T, class X, int N>
std::shared_ptr<T> GetInstancePtr()
{
static std::shared_ptr<T> v(new T);
return v;
}
/**
* @brief 单例模式封装类
* @details T 类型
* X 为了创造多个实例对应的Tag
* N 同一个Tag创造多个实例索引
*/
template<class T, class X = void, int N = 0>
class Singleton {
public:
/**
* @brief 返回单例裸指针
*/
static T* GetInstance()
{
static T v;
return &v;
}
};
/**
* @brief 单例模式智能指针封装类
* @details T 类型
* X 为了创造多个实例对应的Tag
* N 同一个Tag创造多个实例索引
*/
template<class T, class X = void, int N = 0>
class SingletonPtr {
public:
/**
* @brief 返回单例智能指针
*/
static std::shared_ptr<T> GetInstance() {
static std::shared_ptr<T> v(new T);
return v;
}
};
#endif // SINGLETON_H
应用
例子1:
#include "Singleton.h"
typedef Singleton<env> EnvMnr;
#define EnvPtr EnvMnr::GetInstance()
例子2:
#include "Singleton.h"
typedef Singleton<XSerial> xSerial;
#define xSerialPtr xSerial::GetInstance()
typedef Singleton<SerialManager> SerialMnr;
#define xSerialMnr SerialMnr::GetInstance()
好处
1.实现解耦;
2.有些类对象不只是一个,就是不能人人都成为皇帝。比如在一个工程中写了一个串口类,工程中需要3个串口,有个串口需指定为固定用处,在写串口类的时候不能把他写成单例。后续在C++设计模式中会提到。