Simple Singleton Design Pattern in C++

·

2 min read

In this blog, I attempted to create a simple program implementing a singleton design pattern. In a Singleton Design Pattern, only one instance for a class exists.

This is achieved by

  1. Private constructor

  2. Private static object declared in the class

  3. Public static method to get the private static object

  4. Initializing the static class object with a null or nullptr

In the code section below, we have a class named Transformer. The constructor is private. The object is declared static.

In the public section, getObject instantiates the class object. This method ensures to return the same single object everytime it is called. This method can be called without any object as it is static.

Methods setValue and getValue are used to set and get private data member value.

After the class is declared and defined, the class object is initiated to nullptr.

#include <iostream>

class Transformer
{
private:
    int value;
    static Transformer *transformerObject;
    Transformer()
    {

    }
public:
    static Transformer* getObject()
    {
        if(NULL == transformerObject)
        {
            transformerObject = new Transformer();
        }
        return transformerObject;
    }
    void setValue(int value)
    {
        this->value =  value;
    }
    int getValue()
    {
        return value;
    }
};

Transformer* Transformer::transformerObject = nullptr;

void printValue(int input)
{
    std::cout << "Value:" << input << "\n";
}

int main()
{
    Transformer *obj1 = Transformer::getObject();
    printValue(obj1->getValue());
    obj1->setValue(9);
    printValue(obj1->getValue());
    Transformer *obj2 = Transformer::getObject();
    printValue(obj2->getValue());
    return 0;
}

Main has two object names obj1 and obj2. They are assigned the output of getObject. This means that both obj1 and obj2 point to the same instance value.

Obj1 prints the value before and after setting the value to 9. The output is 0 and 9.

Obj2 then prints the value and the output is 9.

💡
Value:0
💡
Value:9
💡
Value:9