Tuesday, 28 August 2018

Singleton : Introduction

The Singleton Design Pattern restricts you to have a single object of the class. It also provides options to call methods of the class without actually having the object of the class.

Query : How to not let other's create an object of the class ?

Response : Constructor is called whenever an object of the class is created. Make all the constructors as private. No one can create an object, not even by inheritance.

Query : How do we create single instance of the class?

Response : A static data member exists as member of class than instance based. There is a single instance of the static variable for all objects of the class. Similar is the case with static methods/functions. A static method can be called even if no object of class is present. Static method can be accessed using class name and scope resolution operator (::). To achieve single instance of the class, we create a class variable which is static and private. We return this variable with help of a public static function. A public static function can be called without class object. It can call the private constructor of the class also.


Simple example Of Singleton in C++

Single.h

#include<iostream>

using namespace std;

Class Single
{
private:
 Single() {};
    Single(const Single &){};
 static Single *instance;
public:
 static Single *getInstance();
};

Single.cpp

#include<single.h>

Single* Single::instance=NULL;

Single* Single::getInstance()
{
 if(!instance)
 {
  instance = new Single();
 }
 return instance;
}



Should Destructor be private or public?

Is it Thread Safe?





Singleton : Is it Thread Safe?

Singleton is not thread-safe in C++. Query : How does multiple threads affects Singleton? Response : Lets assume that no instance of...