Created
February 5, 2025 09:38
-
-
Save kenpower/a51acbb9595b5ca80ef7457a9719d937 to your computer and use it in GitHub Desktop.
Null object Logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
// Logger Interface | |
class Logger { | |
public: | |
virtual void log(const std::string& message) = 0; | |
virtual ~Logger() {} | |
}; | |
// RealLogger - A concrete implementation of Logger | |
class RealLogger : public Logger { | |
public: | |
void log(const std::string& message) override { | |
std::cout << "Logging message: " << message << std::endl; | |
} | |
}; | |
// NullLogger - The Null Object Implementation | |
class NullLogger : public Logger { | |
public: | |
void log(const std::string& message) override { | |
// No operation performed, acts as a null object | |
} | |
}; | |
// Application class that uses Logger | |
class Application { | |
private: | |
Logger* logger; | |
public: | |
// Constructor that takes a logger, defaulting to NullLogger if null | |
Application(Logger* _logger) : logger(_logger) {} | |
void run() { | |
// In the actual logic, you don't need to check if logger is null. | |
logger->log("Application started"); | |
// More application code... | |
logger->log("Application finished"); | |
} | |
}; | |
int main() { | |
// Example 1: Using a RealLogger | |
RealLogger* realLogger = new RealLogger(); | |
Application appWithRealLogger(realLogger); | |
appWithRealLogger.run(); // This will log actual messages | |
std::cout << "---------------------------" << std::endl; | |
// Example 2: Using NullLogger (No logging will occur) | |
NullLogger* nullLogger = new NullLogger(); | |
Application appWithNullLogger(nullLogger); | |
appWithNullLogger.run(); // No logging occurs | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment