vendredi 5 juillet 2019

Singleton implementation using Factory pattern

Since singleton pattern has a number of potential problems, I heard the pattern is getting deprecated in the real industry. So I have implemented a single instance using Factory Pattern and I want to hear from all of you guys if this implementation does not violate any SOLID principle. Any feedbacks are highly appreciated if you think my new implementation causes another side effect.

#include <iostream>

class Logger;

class LoggerFactory {
public:
    Logger & getLogger();
};

class Logger {
private:
    Logger() { std::cout << "Logger Constructed" << std::endl; }

    friend class LoggerFactory;

public:
    Logger & operator<<(std::string message) {
        std::cout << "[log.txt] " << message << std::endl;

        return *this;
    }
};

Logger & LoggerFactory::getLogger() {
    static Logger * logger = nullptr;

    if (logger == nullptr)
        logger = new Logger();

    return *logger;
}



int main() {
    LoggerFactory aa;

    auto x = aa.getLogger();
    x << "1st output";

    auto y = aa.getLogger();
    y << "2nd output";

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire