Skip to content

Instantly share code, notes, and snippets.

@kenpower
Created February 5, 2025 09:38
Show Gist options
  • Save kenpower/a51acbb9595b5ca80ef7457a9719d937 to your computer and use it in GitHub Desktop.
Save kenpower/a51acbb9595b5ca80ef7457a9719d937 to your computer and use it in GitHub Desktop.
Null object Logger
#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