Design and implement a small logger system with configurable handlers. The interviewer may describe this as an object-oriented coding question with handlers such as CapitalHandler, which only logs messages with all capital letters, and NumericHandler, which only logs messages containing numbers.
You are tasked with designing a logger system that allows for configurable logging behavior through the use of different handlers. The system should support adding multiple handlers and each handler should be able to filter messages based on specific criteria. Implement the following classes and methods:
Logger: The main class responsible for logging messages.
addHandler: Method to add a new handler to the logger.log: Method to log messages, which should be passed to each handler.Handler: An abstract base class or interface for handlers.
canHandle: Method to determine if the handler should process a given message.handle: Method to process the message if canHandle returns true.CapitalHandler: A concrete handler that only logs messages with all capital letters.
NumericHandler: A concrete handler that only logs messages containing numbers.
Adding both CapitalHandler and NumericHandler to the logger and logging various messages:
`
logger.addHandler(CapitalHandler())
logger.addHandler(NumericHandler())
logger.log("Hello World") # Should not be logged by either handler logger.log("ALL CAPS") # Should be logged by CapitalHandler logger.log("123 Numbers") # Should be logged by NumericHandler logger.log("ALLCAPS123") # Should be logged by both handlers `
Output for the above example:
ALL CAPS 123 Numbers ALLCAPS123
log method in the Logger class iterates through all handlers and checks if they can handle the message before processing it.Here is a possible implementation in Python:
`python from abc import ABC, abstractmethod
class Handler(ABC): @abstractmethod def canHandle(self, message: str) -> bool: pass
@abstractmethod
def handle(self, message: str) -> None:
pass
class CapitalHandler(Handler): def canHandle(self, message: str) -> bool: return message.isupper()
def handle(self, message: str) -> None:
print(message)
class NumericHandler(Handler): def canHandle(self, message: str) -> bool: return any(char.isdigit() for char in message)
def handle(self, message: str) -> None:
print(message)
class Logger: def init(self): self.handlers = []
def addHandler(self, handler: Handler) -> None:
self.handlers.append(handler)
def log(self, message: str) -> None:
for handler in self.handlers:
if handler.canHandle(message):
handler.handle(message)
logger = Logger() logger.addHandler(CapitalHandler()) logger.addHandler(NumericHandler())
logger.log("Hello World") logger.log("ALL CAPS") logger.log("123 Numbers") logger.log("ALLCAPS123") `
This solution provides a basic logger system with two handlers, CapitalHandler and NumericHandler, and demonstrates how to add handlers and log messages. The output will be as specified in the examples.