-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathabtract_factory.py
More file actions
109 lines (83 loc) · 2.54 KB
/
abtract_factory.py
File metadata and controls
109 lines (83 loc) · 2.54 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from abc import ABC, abstractmethod
import psycopg2
import sqlite3
class Button(ABC):
@abstractmethod
def render(self):
pass
class CheckBox(ABC):
@abstractmethod
def render(self):
pass
class LightButton(Button):
def render(self):
return "Rendering Light Button"
class LightCheckBox(CheckBox):
def render(self):
return "Rendering Light Checkbox"
class DarkButton(Button):
def render(self):
return "Rendering Dark Button"
class DarkCheckbox(CheckBox):
def render(self):
return "Rendering Dark Checkbox"
class UIFactory(ABC):
@abstractmethod
def create_button(self) -> Button:
pass
@abstractmethod
def create_checkbox(self) -> CheckBox:
pass
class LightThemeFactory(UIFactory):
def create_button(self) -> Button:
return LightButton()
def create_checkbox(self) -> CheckBox:
return LightCheckBox()
class DarkThemeFactory(UIFactory):
def create_button(self) -> Button:
return DarkButton()
def create_checkbox(self) -> CheckBox:
return DarkButton()
#Client code
def render_ui(factory: UIFactory):
button = factory.create_button()
check_box = factory.create_checkbox()
return button.render(),check_box.render()
#example usage
light_factory = LightThemeFactory()
dark_factory = DarkThemeFactory()
print(render_ui(light_factory))
print(render_ui(dark_factory))
# Example for database connection
class DatabaseConnection(ABC):
@abstractmethod
def connect(self):
pass
class SQLiteConnection(DatabaseConnection):
def connect(self):
return sqlite3.connect('example.db')
class PostgreSQLConnection(DatabaseConnection):
def connect(self):
return psycopg2.connect(database="test", user="postgres", password="password", host="localhost", port="5432")
class DatabaseFactory(ABC):
@abstractmethod
def create_connection(self):
pass
class MySQLFactory(DatabaseFactory):
def create_connection(self) -> DatabaseConnection:
return SQLiteConnection()
class PostgreSQLFactory(DatabaseFactory):
def create_connection(self) -> DatabaseConnection:
return PostgreSQLConnection()
#Client code
def db_connection(facotry: DatabaseFactory):
db_factory = facotry.create_connection()
conn = db_factory.connect()
print(f'Connected to {conn}')
#Example usage
mysql_factory = MySQLFactory()
postgresql_factory = PostgreSQLFactory()
print('Using MySQL:')
db_connection(mysql_factory)
print('Using PostgreSQL:')
db_connection(postgresql_factory)