Decorator Pattern
The Decorator pattern: adding behaviour to an object by wrapping it in others with the same interface, and how it differs from Python's @ syntax.
Features that can be combined freely, such as logging, retrying and caching around a network client, are hard to add with subclasses: every combination needs a class of its own. The Decorator pattern adds each feature as a wrapper that has the same interface as the object it wraps, so wrappers stack in any combination and the code that uses them cannot tell a wrapped object from a plain one.
This topic opens on that combination problem and the pattern's intent, then reads the participants off the class diagram, where a decorator both is a component and holds one. The template stacks two decorators in Python, Java and TypeScript and shows how a call travels through the stack.
Two examples follow: an HTTP client wrapped in retrying and logging layers, where swapping the order of the layers changes what is logged, and Java's BufferedInputStream, where one wrapper turns ten thousand reads from a file into three. The gotcha separates the pattern from Python's @decorator syntax, which shares the name and the wrapping but not the rest, and the exercise asks you to build a stack of text formatters in the right order.
By the end you can recognise a decorator, predict the result of a stack, and say how Python's @ syntax relates to the pattern.
Contents
8 cardsnot started