What is Decorator pattern?
💻 coding

What is Decorator pattern?

1 min read 255 words
1 min read
ShareWhatsAppPost on X
  • 1The decorator pattern allows adding behavior to individual objects without affecting others in the same class.
  • 2It adheres to the Single Responsibility Principle by dividing functionality between classes with unique concerns.
  • 3Decorator objects implement the interface of the original object, enabling dynamic functionality extension at run-time.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The decorator pattern allows adding behavior to individual objects without affecting others in the same class."

What is Decorator pattern?

In object-oriented programming, the decorator pattern is a design pattern that allows the behaviour to be added to an individual object, either statically or dynamically, without affecting the behaviour of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. The decorator pattern is structurally nearly identical to the chain of responsibility pattern, the difference being that in a chain of responsibility, exactly one of the classes handles the request, while for the decorator, all classes handle the request.

The Decorator design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

What problems can the Decorator design pattern solve?

Responsibilities should be added to (and removed from) an object dynamically at run-time.

A flexible alternative to subclassing for extending functionality should be provided.

When using subclassing, different subclasses extend a class in different ways. But an extension is bound to the class at compile-time and can't be changed at run-time.

What solution does the Decorator design pattern describe?

Define Decorator objects that

implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it and

perform additional functionality before/after forwarding a request.

This enables to work through different Decorator objects to extend the functionality of an object dynamically at run-time.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 1 August 2018 · 1 min read · 255 words

Part of AskGif Blog · coding

You might also like