Última atividade 7 months ago

用 Python 實現資料庫介面,輕鬆切換不同資料庫實作。

timmy revisou este gist 7 months ago. Ir para a revisão

Sem alterações

timmy revisou este gist 7 months ago. Ir para a revisão

1 file changed, 30 insertions

database_interface.py(arquivo criado)

@@ -0,0 +1,30 @@
1 + from abc import ABC, abstractmethod
2 +
3 + # 定義一個資料庫介面,規定大家都要有 connect 方法
4 + class IDatabase(ABC):
5 + @abstractmethod
6 + def connect(self):
7 + pass
8 +
9 + # 具體實作 MySQL 版資料庫
10 + class MySQLDatabase(IDatabase):
11 + def connect(self):
12 + print("連線到 MySQL 資料庫!")
13 +
14 + # 服務類別,同樣透過建構子注入依賴,這次接收的是介面型別
15 + class UserService:
16 + def __init__(self, database: IDatabase):
17 + self.database = database # 不管你是 MySQL、PostgreSQL,都行
18 +
19 + def login(self, username: str):
20 + self.database.connect() # 登入時動態呼叫 connect
21 + print(f"使用者 {username} 登入成功!")
22 +
23 + def main():
24 + db = MySQLDatabase() # 換成任何符合 IDatabase 的實作都可以
25 + user_service = UserService(db) # 注入進去
26 + user_service.login("timmy") # 呼叫登入
27 +
28 + if __name__ == "__main__":
29 + main()
30 +
Próximo Anterior