Codacoda
Back to Academy

design patterns

Decorator

The Decorator pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality. Decorators wrap an object, providing the same interface while adding behavior before or after delegating to the wrapped object. The key participants are the Component (defines the interface), ConcreteComponent (the object being wrapped), Decorator (maintains a reference to a Component and conforms to the Component interface), and ConcreteDecorator (adds responsibilities). Think of ordering coffee: you start with a base coffee and add decorations like milk, sugar, or whipped cream — each add-on wraps the previous order. Use Decorator when you need to add responsibilities to individual objects dynamically and transparently, without affecting other objects.

Use Cases

  • Adding logging, caching, or authentication to services
  • Extending UI components with borders, scrolling, or shadows
  • Stream processing with encryption, compression, or buffering layers
  • Middleware pipelines in web frameworks

Visualization

wraps<<interface>>Component+operation()ConcreteComponent+operation()<<abstract>>Decorator+operation()#wrappedConcreteDecoratorA+operation()addedBehavior()
Speed:1x
Decorator — attaches additional responsibilities to an object dynamicallyStep 1 / 7

Implementation

Output

Click "Run Code" to see output...