单例模式
单例模式(Singleton Pattern)是 最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
有以下注意的点:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
比如我们在写服务器程序时,日志对象实例就应该是单例模式,下面介绍两种实现手法。
代码实现一
#include <iostream>
#include<ctime>
#include<chrono>
#include<iomanip>
using namespace std;
class Log
{
private:
Log(int n = 0) :id(n) //私有构造函数,单例模式只能有一个实例
{
};
int id;
public:
static Log& Instance()
{
static Log slog(1); //第一次Instance()函数调用会构造静态实例slog,后面每次调用会跳过这句,直接返回slog实例
return slog;
}
void Info()
{
//打印日期
auto t = std::chrono::system_clock::now();
auto tNow = std::chrono::system_clock::to_time_t(t);
//std::tm* now = localtime(&tNow); vs2019会报警告
tm* now = new tm;
localtime_s(now, &tNow);
printf("log_id=<%d>\n", id);
//日期打印1
printf("[%d-%d-%d %d:%d:%d]\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday
, now->tm_hour, now->tm_min, now->tm_sec);
//日期打印2
char time[80] = { 0 };
strftime(time, 80, "%Y-%m-%d %H:%M:%S", now);
cout << time << endl;
//日期打印3
std::cout << std::put_time(now, "%Y-%m-%d %H:%M:%S") << endl;
}
};
int main()
{
Log* slog1 = &Log::Instance();
Log* slog2 = &Log::Instance();
//以下三条都是调用一个实例对象来打印日期
slog1->Info();
slog2->Info();
Log::Instance().Info();
}
测试结果:
代码实现二
#include <iostream>
#include<ctime>
#include<chrono>
#include<iomanip>
using namespace std;
class Log
{
private:
Log(int n = 0) :id(n) //私有构造函数,单例模式只能有一个实例
{
};
int id;
public:
static Log* Instance()
{
static Log* slog = new Log(1); //第一次Instance()函数调用会构造静态实例slog,后面每次调用会跳过这句,直接返回slog指针
static RAII_Log sRaii; //静态对象来保证程序结束时new出来的Log能被delete掉
return slog;
}
class RAII_Log
{
public:
~RAII_Log() //程序结束时调用
{
if (Log::Instance())
{
delete Log::Instance();
cout << "delete Log::Instance();" << endl;
}
}
};
void Info()
{
//打印日期
auto t = std::chrono::system_clock::now();
auto tNow = std::chrono::system_clock::to_time_t(t);
//std::tm* now = localtime(&tNow); vs2019会报警告
tm* now = new tm;
localtime_s(now, &tNow);
printf("log_id=<%d>\n", id);
//日期打印1
printf("[%d-%d-%d %d:%d:%d]\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday
, now->tm_hour, now->tm_min, now->tm_sec);
//日期打印2
char time[80] = { 0 };
strftime(time, 80, "%Y-%m-%d %H:%M:%S", now);
cout << time << endl;
//日期打印3
std::cout << std::put_time(now, "%Y-%m-%d %H:%M:%S") << endl;
}
};
int main()
{
Log* slog1 = Log::Instance();
Log* slog2 = Log::Instance();
//以下三条都是调用一个实例对象来打印日期
slog1->Info();
slog2->Info();
Log::Instance()->Info();
}
测试结果如下: