Singleton - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Ensure a class only has one instance, and provide a global point of access to it.

Diagram

disgram

Consequences

  1. Controlled access to sole instance.
  2. Reduced name space.
  3. Permits refinement of operations and representation.
  4. Permits a variable number of instances.
  5. More flexible than class operations.

Implementation

  1. Ensuring a unique instance.
  2. Subclassing the Singleton class.

Sample Code

#include <iostream>
class Singleton
{
public:
	static Singleton& getInstance()
	{
		if (m_pInstance == nullptr)
			m_pInstance = new Singleton();
		return *m_pInstance;
	}
	static void ResetInstance()
	{
		delete m_pInstance; 
		m_pInstance = nullptr;
	}
private:
	static Singleton * m_pInstance;
	Singleton() {};
public:
	void SayHello() { std::cout << "hello"; }
	
	Singleton(Singleton const&) = delete;
	void operator=(Singleton const&) = delete;
};
Singleton * Singleton::m_pInstance = nullptr;

int main()
{
	Singleton::getInstance().SayHello();
	Singleton::getInstance().ResetInstance();
}
⚠️ **GitHub.com Fallback** ⚠️