C++

C++ : Singleton Design Pattern

  • Singleton is a design pattern that is used to make sure that only object of a type (class) exist.
  • Singleton provides just 1 way of accessing the only object that exist.

In the below example we have a random number generator that uses a Singleton design pattern.

Writing Singleton
- Making the constructor private ensures that an object of the singleton is not created.
- The usage of the copy constructor has been disabled by appending = delete to the copy constructor declaration.
- A single static instance of the class (Random) exist that can only be accessed using a static method.
- The usage of the assignment operator has been disabled by appending = delete to the assignment operator.

C++ program shows a way to implement a Singleton class (design pattern)

#include<iostream>
#include<cstdlib>

class Random {

    private:
    // Make the default constructor private.
    Random() {}

    public:
    // Delete the copy constructor function.
    Random ( const Random& ) = delete;

    // Delete the overloading of assignment operator
    Random& operator = (const Random&) = delete;
    static Random& Get() {

        static Random inst_random;
        return inst_random;
    }
     
    // Seed the random number generator.
    void Seed () {
        srand(time(NULL));
    }

    int GenInt () {
        return rand() % 100;
    }   
};

int main() {
    // Below call invokes a copy constructor. 
    // Hence delete the copy constructor function in the class.
    // Random inst = Random::Get();
    Random :: Get().Seed();

    int i = 1;
    std :: cout << "Generating 10 random integers..." << std :: endl;
    while(i<=10) {
        std :: cout << Random::Get().GenInt() << " ";
        i++;
    }   
    return 0;
}

Output

Generating 10 random integers...
7 45 61 85 8 3 5 44 2 75 


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.