Singleton Design Pattern

Singleton pattern is one of the creational pattern.

According to GoF intent of Singleton pattern is to Ensure a class only has one instance, and provide a global point of access to it.


Code :

#include <iostream>

using namespace std;

class Logger {
public:
    static Logger* getInstance();

private:
    Logger(){}                   //Made private don't to create object via constructor
    Logger(Logger *);            //copy constructor is private so it can't be copied
    Logger* operator=(Logger *); //Assignment operator is private

    static Logger *instance;
};

Logger* Logger::instance = NULL;

Logger* Logger::getInstance() {
    if (instance == NULL) {
        instance = new Logger();
        cout << "Creating New Object "<< endl;
    } else {
        cout << "Utilizing Existing Object " << endl;
    }
    return instance;
}

int main()
{
    Logger *inst1 = Logger::getInstance();

    Logger *inst2 = Logger::getInstance();

    Logger *inst3 = Logger::getInstance();

    return 0;
}

Output:

Creating New Object
Utilizing Existing Object
Utilizing Existing Object


No comments:

Post a Comment