设计模式-单体模式
单体模式在使用非常方便,适合于单一的对象,例如全局对象的抽象使用。
需要注意的是单体模式不可继承
// 实现 Singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
class Singleton
{
public:
static Singleton* Instance()
{
if (nullptr == m_Instance)
{
m_Instance = new Singleton();
}
return m_Instance;
}
static void ClearInstance()
{
if (NULL != m_Instance)
{
delete m_Instance;
m_Instance = NULL;
}
}
void Print()
{
printf("hello world");
}
private:
//Singleton模式,隐藏构造函数
Singleton()
{
}
~Singleton()
{
}
static Singleton* m_Instance;
};
Singleton* Singleton::m_Instance = nullptr;
#endif
// 使用 main.cpp
#include "Singleton.h"
int main()
{
Singleton::Instance()->Print();
getchar();
}
原文链接: https://www.cnblogs.com/caimagic/p/6097258.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/244502
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!