2.2 - תבניות מבנה - תרגול
Adapter¶
תרגיל 1¶
חברה קנתה ספרייה חיצונית לניהול קבצים בשם FileStorage. הinterface שלה שונה ממה שהמערכת שלכם מצפה.
# External library - do not change
class FileStorage:
def upload_file(self, file_content: bytes, filename: str, folder: str) -> str:
"""Returns a URL for the file"""
return f"https://storage.example.com/{folder}/{filename}"
def remove_file(self, file_url: str) -> bool:
"""Returns True if it succeeded"""
return True
def retrieve_file(self, file_url: str) -> bytes:
"""Returns the file's content"""
return b"file content"
# The interface your system expects
class AttachmentStore:
def save(self, content: bytes, name: str) -> str: ...
def delete(self, attachment_id: str) -> None: ...
def get(self, attachment_id: str) -> bytes: ...
כתבו FileStorageAdapter שממיר FileStorage לinterface AttachmentStore.
Decorator¶
תרגיל 2¶
יש לכם TaskService שמבצע פעולות על משימות. הוסיפו שני decorators:
TimedTaskService- מודד וכותב כמה זמן כל פעולה לוקחת (בשניות)RetryTaskService- אם פעולה נכשלת (זורקת exception), מנסה שוב עד 3 פעמים
class TaskService:
def get_task(self, task_id: int) -> dict:
import time
time.sleep(0.1) # simulates work
return {"id": task_id, "title": "Task"}
def update_task(self, task_id: int, title: str) -> dict:
import random
if random.random() < 0.5: # 50% chance of failure
raise ConnectionError("Connection failed")
return {"id": task_id, "title": title}
Facade¶
תרגיל 3¶
בנו TaskFlowFacade שמספק שתי פעולות עיקריות:
create_task_with_notification(title, description, owner_id, owner_email)- יוצר משימה ושולח מייל לבעליםclose_project(project_id, owner_id)- מסמן את כל המשימות הפתוחות בפרויקט כ"הושלם" ומארכב את הפרויקט
השתמשו במחלקות פשוטות לdemo: