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)
#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)
#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();
}