Decorator Pattern
In one line
The Decorator pattern wraps an object to add new behavior without modifying the original object's code.
In simple words
The Decorator pattern lets you attach additional behavior to an object at runtime by wrapping it in another object that implements the same interface. The decorator forwards requests to the wrapped object but can add actions before or after the forwarding.
This is an alternative to subclassing for extending functionality. Instead of creating a CoffeeWithMilkAndSugar class, you start with a Coffee object, wrap it in a MilkDecorator, then wrap that in a SugarDecorator. Each decorator adds a small piece of behavior and delegates the rest.
Decorators keep responsibilities single and composable. The same decorator can wrap any object with the right interface, and you can mix and match decorators in any order. JavaScript and TypeScript even have a language-level decorator syntax for classes and methods.
Example
class Coffee { cost() { return 5; } }
function withMilk(coffee) {
return { cost: () => coffee.cost() + 1 };
}
function withSugar(coffee) {
return { cost: () => coffee.cost() + 0.5 };
}
const myCoffee = withSugar(withMilk(new Coffee()));
console.log(myCoffee.cost()); // 6.5Each decorator wraps the coffee and adds to its cost. The final cost is 5 + 1 (milk) + 0.5 (sugar) = 6.5.
Related terms
Related Resources
Related Lessons
- Design Patterns
Decorator is a structural pattern.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.