设计模式-单体模式(C++)

设计模式-单体模式

单体模式在使用非常方便,适合于单一的对象,例如全局对象的抽象使用。
需要注意的是单体模式不可继承

// 实现 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/langzou/p/6097258.html