Design Patterns

Notes and exercises for learning design patterns

View the Project on GitHub Claptar/design-patterns

Exercise 1: Basic Decorator

The scenario

You are building a notification system. The core object is a Notifier that sends messages to users:

class EmailNotifier(Notifier):
    def send(self, recipient: str, message: str) -> None:
        print(f"EMAIL to {recipient}: {message}")

The system works fine. But now two new requirements arrive:

You must add these behaviours without modifying EmailNotifier.


Your task

Part A โ€” add logging

Implement LoggingDecorator. It should:

Expected output:

SENDING notification to alice@example.com
EMAIL to alice@example.com: Meeting at 3pm
SENT notification to alice@example.com

Part B โ€” add uppercasing

Implement UppercaseDecorator. It should:

Expected output when wrapping EmailNotifier directly:

EMAIL to bob@example.com: SERVER IS DOWN

Part C โ€” compose them

Wrap EmailNotifier with both decorators so that the message is uppercased and the send is logged.

Expected output:

SENDING notification to bob@example.com
EMAIL to bob@example.com: SERVER IS DOWN
SENT notification to bob@example.com

Skeleton

See exercise1.py.


What to focus on


Solution ยท Exercise 2