Decorator in Practice: Streams, Middleware, and UI Enhancement
You'll learn: How the Decorator pattern solves real-world problems in I/O operations, web servers, and user interfaces.
Why Decorators Matter in Real Systems
The Decorator pattern isn't just academic—it's everywhere in production code. Three domains especially benefit from dynamic behavior wrapping: streams, middleware, and UI components.
Streams: Layering I/O Behaviors
Think of reading a file that's compressed and encrypted. You could create CompressedEncryptedFileReader, but what about just compressed? Just encrypted? That's 4+ classes for every combination.
Instead, streams use decorators: wrap a basic stream with a compression decorator, then wrap that with an encryption decorator. Each wrapper adds one responsibility while passing through the core reading behavior. You compose functionality at runtime by stacking wrappers.
Middleware: Request Processing Pipelines
Web servers often need logging, authentication, compression, and caching. Middleware chains are decorators—each middleware wraps the next handler, adding its behavior (like checking credentials) before forwarding the request. You can reorder or remove middleware without changing core routing logic. Each decorator in the chain decides whether to enhance, block, or simply forward.
UI Enhancement: Adding Visual Behaviors
Consider a text display component. You might need it with a border, or with scrollbars, or with both. Decorators let you wrap the base component: a BorderDecorator adds border-drawing, a ScrollDecorator adds scroll behavior. You can mix and match at runtime based on user preferences without creating BorderedScrollableTextDisplay and every other combination class.
The Common Thread
All three scenarios share a pattern: adding layers of responsibility around a core object without altering it or creating exponential class combinations. Each decorator wraps and forwards, enhancing behavior transparently.
Key Takeaway: Decorators shine in streams (layered I/O), middleware (request pipelines), and UI (dynamic visual features)—anywhere you need flexible, composable behavior enhancement without class explosion.