Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
The Problem
Inheritance for extending behavior leads to a class explosion: BufferedEncryptedCompressedStream, UnbufferedEncryptedStream, BufferedStream... every combination needs its own class. You can't add buffering to an existing object at runtime — you'd have to create a new instance.
Structure
Execution Walkthrough
Component interface
Stream interface defines read()/write(). All concrete streams and decorators implement this exact interface.
Base component
Decorator base
Concrete decorators
Compose at runtime
Code Comparison
Full C++ Implementation
Participants
Where it is used
C++ I/O streams
std::ifstream wrapped by boost::iostreams filtering — buffered, compressed, encrypted layers stacked.
Middleware stacks
FastAPI/Express: auth → rate-limit → logging → handler. Each middleware wraps the next.
Python decorators
@lru_cache, @staticmethod — each wraps a function and adds caching or binding.
Network sockets
Raw socket → TLS → buffering → compression. Same interface, composed at connection time.