Design Patterns

Notes and exercises for learning design patterns

View the Project on GitHub Claptar/design-patterns

Exercise 1: Virtual Proxy

Scenario

You are building a reporting dashboard. The sidebar shows a list of available reports — title and author — fetched on every page load.

Each report is generated by a RealReportService. Generating a report is expensive: it involves reading from a database, assembling a PDF, and can take several seconds. Only one or two reports are actually downloaded per session, but the current code creates a RealReportService for every report in the list. Most of those reports are generated and then thrown away unread.

Your task is to fix this with a virtual proxy.

What you need to implement

Open exercise1.py and implement LazyReportProxy.

The proxy must:

The interface

class ReportService(ABC):
    def get_metadata(self) -> ReportMetadata: ...
    def get_content(self) -> str: ...

Running the tests

pytest exercise1.py -v

Hints

def _load(self):
    if self._real is None:
        self._real = RealReportService(...)
    return self._real

What to notice when it works

Run the tests and observe the output. The [RealReportService] Generating... message should only appear when get_content() is called, not when get_metadata() is called. If you create fifty proxies and only request content from one, only one generation message appears.