单例模式
单例模式作用
1.只能创建一个对象,节约资源。 2.保证他是唯一的实例,有些设计需要在不同的模块调用同一个实例对象。
懒汉式
线程安全的懒汉式-单例模板
#include <mutex>
template <class T>
class Singleton
{
public:
static T* GetSingleton()
{
if(pSingleton == nullptr)
{
mxt.lock();
if(pSingleton == nullptr)
{
pSingleton = new T();
}
mxt.unlock();
}
return pSingleton;
}
static void Destroy()
{
mxt.lock();
if (pSingleton != nullptr)
{
delete pSingleton;
pSingleton = nullptr;
}
mxt.unlock();
}
private:
static T* pSingleton;
static std::mutex mxt;
};
template <class T>
std::mutex Singleton<T>::mxt;
template <class T>
T* Singleton<T>::pSingleton = nullptr;
使用单例模板的类
#include "Singleton/Singleton.h"
class GirlFriend
{
public:
friend class Singleton<GirlFriend>;
void show() const
{
std::cout << "身高:" << height << std::endl;
std::cout << "年龄:" << age << std::endl;
}
private:
GirlFriend() = default;
~GirlFriend() = default;
int age = 18;
int height = 166;
};
main.cpp
#include <iostream>
#include "GirlFriend/GirlFriend.h"
#include "Singleton/Singleton.h"
int main() {
Singleton<GirlFriend>::GetSingleton()->show();
std::cout << "Hello, World!" << std::endl;
return 0;
}
结果
身高:166 年龄:18 Hello, World!
|