Singleton in C++

In this tutorial, we will learn about Singleton in C++.

In C++ Singleton pattern is a design pattern that puts a limit on a class to instantiate its multiple objects.

The ‘Singleton’ term uses also in mathematics where it is known as a ‘Unit Set’ is a set exactly one element.

In the Singleton pattern, A class can produce only one instance or object in the complete execution of a program. Thus, it is a way of defining a class where a class needs only one object. It should not have multiple objects at any cost.

 

Requirements for Singleton Design Pattern in C++

  1.  Static member
  2. private constructor
  3. static function

Example:

#include<iostream>
using namespace std;
class Singleton
{
    private:
        static Singleton*i;

        Singleton();

    public:
        static Singleton* getInstance();
};
Singleton* Singleton::i = 0;

Singleton* Singleton::getInstance()
{
    if (i== 0)
    {
        i= new Singleton();
    }

    return i;
}

Singleton::Singleton()
{}

int main()
{
    Singleton* p = Singleton::getInstance(); 
    Singleton* q = Singleton::getInstance();

    cout << p << endl;//both will print same address
    cout << q << endl;
}

Global Access:

The instance of a class should be globally accessible. so that each class can use it.

Only one Instance:

It should have only one instance.

Early Initialization:

It initializes a class whether it is being used or not.

Lazy Initialization:

And in lazy we have to initialize a class when it requires.

Advantages:

Single Access Point Ex:-Logger, Database Connection

Save Memory Ex:- only one need of instance so why create so many.

Usage:

Logger:

The log file generations use singleton class

Game setting

Hardware interface access

Cache

 

Next Topic -: Get all the files in a directory using  C++

Leave a Reply

Your email address will not be published. Required fields are marked *