teacher
Sign in

Decorator

Wrap an object in another with the same interface to add behaviour such as logging, retries or caching, and stack the layers freely.

25 min3 interactive

The problem it solves

You have a Fetcher that downloads a URL. Now you want logging, retries and caching. Three ways to get there:

  • Edit the class for each feature. It grows into one tangled class, and every user pays for features they do not need.
  • Subclass per combination. Three features give 8 combinations (LoggingRetryFetcher, RetryCachingFetcher, ...). Four features give 16.
  • Decorate: write one small class per feature, each implementing Fetcher and holding another Fetcher. Stack them in any order.

A decorator is a wrapper that has the same interface as the object it wraps. It forwards the call, adding behaviour before or after.

1 of 6