Decorator
Wrap an object in another with the same interface to add behaviour such as logging, retries or caching, and stack the layers freely.
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
Fetcherand holding anotherFetcher. 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