Structural Patterns  «Prev  Next»

Decorator Pattern


The Decorator pattern enables you to add or remove object functionality without changing the external appearance or function of the object. It changes the functionality of an object in a way that is transparent to its clients by using an instance of a subclass of the original class that delegates operations to the original object. The Decorator pattern attaches additional responsibilities to an object dynamically to provide a flexible alternative to changing object functionality without using static inheritance

Decorator Pattern
Decorator Pattern Java Code


The following lists the benefits of using the Decorator pattern:
  1. More flexibility than static inheritance.
  2. Avoids feature-laden classes high up in the hierarchy
  3. Simplifies coding because you write a series of classes, each targeted at a specific part of the functionality, rather than coding all behavior into the object
  4. Enhances the object's extensibility because you make changes by coding new classes.

When To Use:

You should use the Decorator pattern when:
  1. You want to add responsibilities to individual objects dynamically and transparently, that is without affecting other objects
  2. You want to add responsibilities to the object that you want to change in the future
  3. When extension by static sub-classing is impractical.