|
1 | | - |
| 1 | +# dependency_injection.py |
| 2 | + |
| 3 | +class Logger: |
| 4 | + """A simple Logger class to log messages.""" |
| 5 | + |
| 6 | + def log(self, message): |
| 7 | + print(f"[LOG]: {message}") |
| 8 | + |
| 9 | + |
| 10 | +class FileLogger(Logger): |
| 11 | + """A logger that writes logs to a file.""" |
| 12 | + |
| 13 | + def __init__(self, filename="app.log"): |
| 14 | + self.filename = filename |
| 15 | + |
| 16 | + def log(self, message): |
| 17 | + with open(self.filename, "a") as file: |
| 18 | + file.write(f"[LOG]: {message}\n") |
| 19 | + print(f"Logged to file: {message}") |
| 20 | + |
| 21 | + |
| 22 | +class Application: |
| 23 | + """Application class demonstrating dependency injection.""" |
| 24 | + |
| 25 | + def __init__(self, logger: Logger): |
| 26 | + """Inject a logger dependency via the constructor.""" |
| 27 | + self.logger = logger |
| 28 | + |
| 29 | + def run(self): |
| 30 | + """Simulate running the application.""" |
| 31 | + self.logger.log("Application has started.") |
| 32 | + self.logger.log("Performing some tasks...") |
| 33 | + self.logger.log("Application is shutting down.") |
| 34 | + |
| 35 | + |
| 36 | +# Example Usage |
| 37 | +if __name__ == "__main__": |
| 38 | + console_logger = Logger() # Injecting a Console Logger |
| 39 | + app1 = Application(console_logger) |
| 40 | + app1.run() |
| 41 | + |
| 42 | + print("\nSwitching to FileLogger...\n") |
| 43 | + |
| 44 | + file_logger = FileLogger() # Injecting a File Logger |
| 45 | + app2 = Application(file_logger) |
| 46 | + app2.run() |
0 commit comments