StructuralverifiedVerified

Decorator

Attaches additional responsibilities to an object dynamically by wrapping it in decorator objects that share the same interface.

Coming Soon

errorWhat Problem Does the Decorator Pattern Solve?

Extending behavior through subclassing leads to a class explosion when many optional, combinable features exist. Each combination requires a new subclass, and adding a feature retroactively forces changes to an ever-growing inheritance hierarchy that becomes brittle and hard to maintain.

check_circleHow the Decorator Pattern Works

Define a component interface that both the base object and all decorators implement. Each decorator holds a reference to a component and delegates calls to it before or after applying its own behavior. Decorators can be stacked in any order at runtime, composing features without subclassing.

Decorator Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Decorator Pattern in the Real World

Think of adding espresso shots and syrups to a coffee order. A plain coffee is the base component. Each addition—an espresso shot, vanilla syrup, oat milk—is a decorator that wraps the previous cup, adding its own cost and flavor. You can combine them in any order without the café needing a separate menu item for every combination.

Frequently Asked Questions

helpWhat is the difference between Decorator and inheritance?

Inheritance adds behavior at compile time and creates a rigid class hierarchy. Decorator adds behavior at runtime by wrapping objects, and multiple decorators can be composed freely. Use Decorator when you need to mix and match behaviors without creating a subclass for every combination.

helpHow does the Decorator pattern relate to TypeScript decorators?

TypeScript's @decorator syntax (stage 3 proposal) applies metadata and behavior modifications at class definition time. The GoF Decorator pattern wraps object instances at runtime. They share the concept of 'adding behavior' but operate at different levels — compile-time vs runtime.