Design Patterns Explained
  • Getting Started
  • SOLID Principles
    • Single Responsibility Principle
    • Open / Closed Principle
    • Liskov Substitution Principle
    • Interface Segregation Principle
    • Dependency Inversion Principle
  • Design Patterns
    • Creational Patterns
      • Abstract Factory Pattern
      • Builder Pattern
      • Factory Pattern
      • Prototype Pattern
      • Singleton Pattern
    • Behavioral Patterns
      • Chain Of Responsibility Pattern
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
        • Example 1
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
        • Example 1
      • Template Method Pattern
      • Visitor Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Decorator Pattern
      • Facade Pattern
      • Flyweight Pattern
      • Proxy Pattern
  • Roadmap
Powered by GitBook
On this page
  • Intent
  • When to use
  • Structure
  • Note
  • Examples

Was this helpful?

  1. Design Patterns
  2. Structural Patterns

Decorator Pattern

PreviousComposite PatternNextFacade Pattern

Last updated 4 years ago

Was this helpful?

Intent

Attach additional responsibilities to an object dynamically. Also provides a flexible alternative to subclassing for extending functionality.

When to use

  1. Use the Decorator pattern when you need to be able to assign extra behaviors to objects at runtime without breaking the code that uses these objects.

  2. If you want responsibilities to be withdrawn dynamically.

  3. When extending by subclassing is impractical, as sometimes large number of extensions would produce and explosion of subclasses to support every combination.

  4. When it is not possible to extend by subclassing, as some classes are final classes, and maybe comming from an external library where it is not possible to modify.

Structure

  • Component: defines the interface for objects that can have responsibilities added to them dynamically.

  • ConcreteComponent: defines an object to which the additional responsibilities can be attached.

  • Decorator: maintains a reference to a Component object and defines an interface that conforms to Component's interface.

  • ConcreteDecorator: adds responsibilities to the component.

Note

Decotator can be implemented either as an interface or an abstract class, GoF recommend imitting the abstract class as there's no need to define a class when you only need to add one responsibility, and directly merge it by forwarding requests to the component in the ConcreteDecotrators.

Examples

Source Code

UML

// TODO

// TODO

You can find the tests .

here
Example 1
Example 2