לדלג לתוכן

2.2 תבניות מבנה תרגול

Adapter

תרגיל 1

חברה קנתה ספרייה חיצונית לניהול קבצים בשם FileStorage. הממשק שלה שונה ממה שהמערכת שלכם מצפה.

# ספרייה חיצונית - אסור לשנות
class FileStorage:
    def upload_file(self, file_content: bytes, filename: str, folder: str) -> str:
        """מחזיר URL לקובץ"""
        return f"https://storage.example.com/{folder}/{filename}"

    def remove_file(self, file_url: str) -> bool:
        """מחזיר True אם הצליח"""
        return True

    def retrieve_file(self, file_url: str) -> bytes:
        """מחזיר את תוכן הקובץ"""
        return b"file content"


# הממשק שהמערכת שלכם מצפה לו
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 לממשק AttachmentStore.

Decorator

תרגיל 2

יש לכם TaskService שמבצע פעולות על משימות. הוסיפו שני decorators:

  1. TimedTaskService - מודד וכותב כמה זמן כל פעולה לוקחת (בשניות)
  2. RetryTaskService - אם פעולה נכשלת (זורקת exception), מנסה שוב עד 3 פעמים
class TaskService:
    def get_task(self, task_id: int) -> dict:
        import time
        time.sleep(0.1)  # מדמה עבודה
        return {"id": task_id, "title": "משימה"}

    def update_task(self, task_id: int, title: str) -> dict:
        import random
        if random.random() < 0.5:  # 50% סיכוי לכשל
            raise ConnectionError("חיבור נכשל")
        return {"id": task_id, "title": title}

Facade

תרגיל 3

בנו TaskFlowFacade שמספק שתי פעולות עיקריות:

  1. create_task_with_notification(title, description, owner_id, owner_email) - יוצר משימה ושולח מייל לבעלים
  2. close_project(project_id, owner_id) - מסמן את כל המשימות הפתוחות בפרויקט כ"הושלם" ומארכב את הפרויקט

השתמשו במחלקות פשוטות לdemo:

class SimpleTaskRepo:
    tasks = []
    def create(self, title, description, owner_id): ...
    def find_open_by_project(self, project_id): ...
    def mark_done(self, task_id): ...

class SimpleProjectRepo:
    def archive(self, project_id): ...

class SimpleEmailService:
    def send(self, to, subject, body): ...