Singleton Pattern
Introduction:
Singleton pattern is a creational design pattern that ensures only one instance of the class, and provide global point of access to it.
Singleton pattern resolves two issues,
- Ensure single instance of a class - Sometimes we need to have only instance of the class for example shared files like persistency DB, some database files.
This can't be achieved by the normal constructor. Because constructor call must always returns a new object (new operator).
In singleton pattern, when client ask for new objects, it returns the old one instead of the newly created object.
- Provide global access point to instance - Using global variables directly is unsafe , and anyone can overwrite the value.
Singleton pattern provides the global access point to the instance as same as global variable. Also, it protects from others to overwrite its value.
When to use,
- When application needs only one instance of the object, and also require global access to it. Additionally lazy initialization.
How to use,
- Move default constructor to private field. This protects others from creating this class instance by calling new operator.
- Declare a static instance of the object as private field.
- Define a static method "getInstance" in public field. This method creates an instance of its own class only once, and return the same object whenever this function gets invoked.
- getInstance() static method is only exposed to others. If any class wants to create the object of this class, it can only call getInstance() object. Direct object creation is blocked by moving the default constructor to private field.
Note:
What if more than one client invokes "getInstance" method simultaneously? We need to protect the object getting created twice.
We achieve this by std::call_once. It executes the callable object exactly once, even if called concurrently from several threads.
In detail:
- If, by the time std::call_once is called, flag (std::once_flag) indicates that f was already called, std::call_once returns right away.
UML diagram:

Implementation:
class CPublisher
{
private:
static std::shared_ptr<CPublisher> publisher;
static std::once_flag s_once;
CPublisher()
{
}
public:
static std::shared_ptr<CPublisher> getPublisher()
{
std::call_once(s_once, [&] {publisher = std::shared_ptr<CPublisher>(new CPublisher); });
return publisher;
}
};
std::shared_ptr<CPublisher> CPublisher::publisher = nullptr;
once_flag CPublisher::s_once;
class CTravelAgency
{
private:
std::shared_ptr<CPublisher> publisher;
public:
CTravelAgency()
{
publisher = CPublisher::getPublisher();
}
};
Source code : https://github.com/krishnaKSA/design_patterns_cplusplus/blob/main/ObserverPattern/OberverPattern.hpp