Sunday, February 2, 2020

Singleton Design Pattern

    A class is defined such that the class possesses only one instance and gives global support to that instance. So, let's discuss in the simpler language of OOP. Consider you define a class 'S', and you try to create multiple objects in main. In respect of the singleton design pattern, you should define the class S such that it should allow the creation of only one object of that class.

   An easy example of a Singleton design pattern you can think of any online multi-player game. Let's say your most favorite; PUBG. Consider an instance of PUBG game running on your account, and you try to login from another device on the same account. In this situation, instead of starting a new instance of your game, the previous instance continues running preventing the re-instantiating the game.

   Now how to create such class? So, the class should contain 3 main components:
i) A private static member: which is an instance/object of the class: as the definition of Singleton DP says, there should be only one instance of an object. Here, we define the instance as 'static' to globalize it and private, so that it should not be re-defined again.
ii) A private constructor: Yeah, people are smart enough so they can create multiple objects by calling its constructor. So, we declare it as private.
and, the third and most important:
iii) A public function: which returns a pointer pointing to the address of the instance. Yes, most important because, a class is of no use without a public member present in it. Yes, funny isn't it? The reason is, you should be able to interact with the instance from your main program.

Example code for the Singleton design pattern is given below:

#include<iostream>

class Singleton{                                                 //By default private if nothing mentioned
             static Singleton instance;                 //A static instance of the object
             Singleton(){                                        //Private constructor
                           std::cout<<"Singleton Contructor"<<std::endl;
             }
             public:
             static Getinstance(){                         //a function which which returns the instance

                           if(instance == NULL)        //this creates instance when there is'nt created one
                                      instance = new Singleton();
                           return instance;
             }

};







References:
https://www.youtube.com/watch?v=0dSDJJzWqQI


12 comments:

Course Project: 3 Lane Car Game

Course Project Title:  3 lane car racing game Course Project Description:              The aim of our course project is to implement...