×

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton pattern is that it provides a global point of access to the class and ensures it has only one instance. Similar to a global variable that can be used everywhere in the program, a singleton object can be used anywhere.

Advnatges of Singleton:

Similar to global variables, singleton has similar advantages and disadvantages.

  1. Provides control over the object's allocation and destruction.
  2. This method provides thread-safe access to the global state of an object.
  3. Pollutes the global namespace by preventing it from being used.

We need a static member, private constructor, and static function in the singleton design pattern class.

Example:

#include <iostream>
using namespace std;
class Singleton {
    private:
   static Singleton *instance;
   int data;
   protected:
    Singleton() {
      data = 0;
   }
   public:
   static Singleton *getInstance() {
      if (instance==0){
      instance = new Singleton;
      }
      return instance;
   }
   int getData() {
      return this -> data;
  }
   void setData(int data) {
      this -> data = data;
   }
};


Singleton *Singleton::instance = 0;
int main(){
   Singleton *s = s->getInstance();
   Singleton *s1 = s1->getInstance();
   Singleton *s2 = s2->getInstance();
   cout << s->getData() << endl;
   s->setData(100);
    s1->setData(200);
    s2->setData(300);
   cout << s->getData() << endl;
    cout << s1->getData() << endl;
    cout << s2->getData() << endl;
   return 0;
}

Output:

C++ singleton design pattern

Explanation:

In the above code, we have created a class called as singleton. In the code, we have created an object for the singleton class by checking that no other object is created for the class. In the code, three instances, s,s1, and s2, are created for the class singleton. We have set the data values as 100 for the s instance and 300 for the s1 instance, and 300 for s2. Here we have set different values, for instance, but the output is similar. This is due to the properties of the singleton design pattern, which is that it can create only one instance for the class


Related Topics

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.