|
| 1 | +# Define common Interface |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | + |
| 5 | + |
| 6 | +class Notifier(ABC): |
| 7 | + @abstractmethod |
| 8 | + def send(self, message: str): |
| 9 | + ... |
| 10 | + |
| 11 | + |
| 12 | +# Implement the concreate Component (Basic Email Notification) |
| 13 | + |
| 14 | +class EmailNotifier(Notifier): |
| 15 | + def send(self, message: str): |
| 16 | + print(f"Sending EMAIL with message: {message}") |
| 17 | + |
| 18 | + |
| 19 | +# Create the Base Decorator |
| 20 | + |
| 21 | +class NotifierDecorator(Notifier): |
| 22 | + def __init__(self, wrapper: Notifier): |
| 23 | + self._wrapper = wrapper |
| 24 | + |
| 25 | + def send(self, message: str): |
| 26 | + self._wrapper.send(message) |
| 27 | + |
| 28 | + |
| 29 | +# Create Concreate Decorator (SMS, Slack, Facebook) |
| 30 | + |
| 31 | +class SMSNotifier(NotifierDecorator): |
| 32 | + def send(self, message: str): |
| 33 | + super().send(message) |
| 34 | + self.send_sms(message) |
| 35 | + |
| 36 | + def send_sms(self, message: str): |
| 37 | + print(f"Sending SMS with message: {message}") |
| 38 | + |
| 39 | + |
| 40 | +class FacebookNotifier(NotifierDecorator): |
| 41 | + def send(self, message: str): |
| 42 | + super().send(message) |
| 43 | + self.send_facebook(message) |
| 44 | + |
| 45 | + def send_facebook(self, message: str): |
| 46 | + print(f"Sending Facebook with message: {message}") |
| 47 | + |
| 48 | + |
| 49 | +class SlackNotifier(NotifierDecorator): |
| 50 | + def send(self, message: str): |
| 51 | + super().send(message) |
| 52 | + self.send_slack(message) |
| 53 | + |
| 54 | + def send_slack(self, message: str): |
| 55 | + print(f"Sending Slack with message: {message}") |
| 56 | + |
| 57 | + |
| 58 | +# Client Code (Runtime composition with Decorators) |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + # Basic notifier (email only) |
| 62 | + notifier = EmailNotifier() |
| 63 | + |
| 64 | + # wrap with SMS and Slack decorators |
| 65 | + notifier = SMSNotifier(notifier) |
| 66 | + notifier = SlackNotifier(notifier) |
| 67 | + notifier = FacebookNotifier(notifier) |
| 68 | + |
| 69 | + # Client Sends one message - it flows through all decorators |
| 70 | + notifier.send("Alert: Server CPU usage exceeded 90% threshold") |
| 71 | + |
| 72 | + |
| 73 | +# Addition of numbers using a decorators |
| 74 | + |
| 75 | +def sumx(func): |
| 76 | + def wrapper(*args, **kwargs): |
| 77 | + result = sum(args) |
| 78 | + return func(result, **kwargs) |
| 79 | + return wrapper |
| 80 | + |
| 81 | +@sumx |
| 82 | +def sum_numbers(result): |
| 83 | + return f"Sum of numbers is: {result}" |
| 84 | + |
| 85 | +print(sum_numbers(1, 3, 4, 8, 9)) |
0 commit comments