Singleton - shoonie/StudyingDesignPattern GitHub Wiki
Ensure a class only has one instance, and provide a global point of access to it.
- Controlled access to sole instance.
- Reduced name space.
- Permits refinement of operations and representation.
- Permits a variable number of instances.
- More flexible than class operations.
- Ensuring a unique instance.
- Subclassing the Singleton class.
#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();
}