1. 程式人生 > >C++ 單例設計模式

C++ 單例設計模式

單例模式是指只有一個例項物件,方法是把建立類的建構函式以及拷貝函式放在private裡

#include<iostream>
#include<stdlib.h>
using namespace std;

class Singleton
{
private:
	Singleton() {}   // 不能通過常規手段生成物件
	~Singleton() {}
	Singleton(const Singleton &) {}
	Singleton & operator = (const Singleton &) {}
	static Singleton *_ins;
public:
	static Singleton *getInstance()
	{
		if (_ins == nullptr)
			_ins = new Singleton;
		return _ins;
	}

	static void releaseInstance()
	{
		if (_ins != nullptr)
		{
			delete _ins;
			_ins = nullptr;
		}
			
	}
};

Singleton * Singleton::_ins = nullptr;

int main()
{
	Singleton *ps = Singleton::getInstance();
	Singleton *ps1 = Singleton::getInstance();
	Singleton *ps2 = Singleton::getInstance();

	cout << ps << endl;
	cout << ps1 << endl;
	cout << ps2 << endl;

	Singleton::releaseInstance();
	system("pause");
	return 0;
}