Design Patterns

Notes and exercises for learning design patterns

View the Project on GitHub Claptar/design-patterns

Exercise 1: Method Chain — Logging Pipeline

Goal

Build a logging pipeline using the Chain of Responsibility method chain pattern.

A log message has a level:

DEBUG = 1
INFO  = 2
WARNING = 3
ERROR = 4

A handler is configured with a minimum level. When a message arrives, the handler processes it if the message level is exactly its own level, and passes it along otherwise. At the end of the chain, unhandled messages are silently dropped.


Part A — build the chain

Implement:

Wire them and verify the output matches the expected section below.


Part B — trace the chain

Add a name attribute to the base handler. Before each handler either processes or passes a message, print a trace line:

[DebugHandler] received DEBUG — processing
[DebugHandler] received INFO — passing along
[InfoHandler] received INFO — processing

This makes the chain’s decision-making visible. Run the same messages from Part A with tracing on.


Expected output (Part A, no tracing)

[DEBUG] hello from debug
[INFO]  user logged in
[WARN]  disk usage at 80%
[ERROR] database connection failed

Skeleton

See exercise1.py.


Hints


Back to notes · Exercise 2