首先科普下单例模式的概念。
单例模式,本质上就是保证某个类实例在程序生存周期有且只有一个实例。
优点嘛,可以方便各个模块访问,被访问但不会一直创建new新的实例,始终只有这一个,可以节省资源。
最经典的用例便是用在日志记录模块,工程中可能很多地方都会进行日志的记录,每处记录如果都要创建新的日志类实例,好像太频繁了,很浪费资源的。这时候,单例类可以保证只有一个类对象,而不会一直new新的出来。直接访问就可以了。
下面我们会提供一个c++单例模板,其中核心便是使用了模板跟一个静态对象来保证其生存周期一直存在,供程序使用
template<typename T>
class CSingleton
{
public:
static T& GetInstance()
{
static T me;
return me;
}
};
.h
#ifndef LOGGER_H
#define LOGGER_H
#include "singleton.h"
class Logger:public CSingleton<Logger>
{
public:
Logger();
void print();
private:
int m_count;
};
#endif // LOGGER_H
.cpp
#include "logger.h"
#include <iostream>
Logger::Logger()
{
m_count=0;
}
void Logger::print()
{
m_count++;
std::cout<<"Logger is exist! value is :"<<m_count<<std::endl;
}
#include "logger.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
new Logger();
for(int i=0;i<5;i++)
Logger::GetInstance().print();
return 0;
}
Done!