C++设计模式 单例模式饿汉式

#include<iostream>
using namespace std;

class Singleton
{
public:
	//提供全局访问点,提供访问点的函数也必须是静态的,否则外界就无法调用该函数
	static Singleton* GetSingleton()
	{
		return single;
	}
	static void DeleteSingleton()
	{
		if (NULL != single)
		{
			cout << "删除单例对象" << endl;
			delete single;
		}
	}
protected:
private:
	static Singleton* single;
	//构造函数私有化
	Singleton()
	{
		cout << "构造函数被调用" << endl;
	}
};
//饿汉式的关键点:类静态成员的初始化代码会在main函数执行之前
Singleton * Singleton::single = single = new Singleton();

int main(int argc, char **argv)
{
	Singleton * single_example = Singleton::GetSingleton();
	Singleton * single_example2 = Singleton::GetSingleton();
	Singleton::DeleteSingleton();
	getchar();
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_15054345/article/details/87190688