DP: Singlton

The Singleton ensures that only one instance of a class exists and provides a global access point to it. It is commonly used for logging systems, hardware drivers, configuration managers, and resource controllers in embedded systems.

Instead of allowing multiple instances, the constructor is hidden and a static method returns the single instance.

  • Ensures one instance
  • Avoid overuse (can behave like a global variable)

C Example (Singleton using static instance)

c
#include <stdio.h>

typedef struct {
    int value;
} Logger;

Logger* getLogger() {
    static Logger instance;  // only one instance
    return &instance;
}

int main() {
    Logger* log1 = getLogger();
    Logger* log2 = getLogger();

    log1->value = 10;
    printf("%d\n", log2->value); // same instance

    return 0;
}

C++ Example (Private Constructor + static function)

cpp
#include <iostream>
using namespace std;

class Logger {
private:
    Logger() {}
public:
    static Logger& getInstance() {
        static Logger instance; // thread-safe in C++11+
        return instance;
    }

    void log() { cout << "Logging...\n"; }
};

int main() {
    Logger::getInstance().log();
}