-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.py
More file actions
52 lines (39 loc) · 1.69 KB
/
Copy path5.py
File metadata and controls
52 lines (39 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 5. D => Dependency Inversion Principle (DIP)
# High Level Modules should not depend on Low Level Module,
# both should depends on abstractions.
class ClientGmail:
def send_mail(self, recipient, subject, body):
# write your email send logic
pass
class EmailService:
def __init__(self):
self.gmail_client = ClientGmail()
def send_mail(self, recipient, subject, body):
self.gmail_client.send_mail(recipient, subject, body)
# In this example the EmailService class directly depend on the GmailClient
# a low-level module that implements the details of sending emails using the Gmail API.
# This violates the DIP because the high-level EmailService module is tightly coupled
# to the low-level GmailClient module.
# To adhere to the DIP as -
class EmailClient:
def send_mail(self, recipient, subject, body):
raise NotImplementedError
class GmailClient(EmailClient):
def send_mail(self, recipient, subject, body):
# Send email logic is here
pass
class OutlookClient(EmailClient):
def send_mail(self, recipient, subject, body):
# send email logic is here
pass
class EmailService:
def __init__(self, email_client):
self.email_client = email_client
def send_email(self, recipient, subject, body):
self.email_client.send_email(recipient, subject, body)
# Usages
gmail_client = GmailClient()
email_service = EmailService(gmail_client)
email_service.send_email("niranjan@gmail.com", "Test subject", "Test email body message")
# Now, the EmailService class depends on the EmailClient abstraction, and the low level email
# client implementations (GmailClient and OutlookClient) depend on the abstraction.