Intermediate Topic 25 of 50 Software Engineering
Decorator Pattern
Adding behavior by wrapping objects.
How it works
The decorator pattern attaches additional behavior to an object dynamically by wrapping it in another object that implements the same interface and forwards calls to the wrapped one, adding work before or after. Decorators can be stacked in different combinations, which avoids an explosion of subclasses and respects the single-responsibility principle.
Step-by-step walkthrough
- A core object offers an operation.
- Decorator 1 wraps it and adds behavior, such as logging.
- Decorator 2 wraps that, such as compression.
- The client uses the outermost object.
- Features stack in any combination without subclasses.
Where it is used
Java I/O streams such as BufferedReader wrapping FileReader, adding logging, caching, compression or authorization to services, UI scrollbars and borders, middleware chains and Python function decorators use this idea.
Common pitfall
Long chains of wrappers are hard to debug and the order of decoration matters. Identity checks and type tests on wrapped objects can fail. A decorator must preserve the interface contract. Too many small decorator classes complicate configuration. Use it when behavior must be added and removed flexibly at runtime.
Where it fits in the course
Decorator Pattern is topic 25 of 50 in Software Engineering, rated Intermediate. It follows Strategy Pattern. The next topic is Dependency Injection.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Software Engineering quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Software Engineering quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Decorator Pattern?
Where do people use Decorator Pattern?
What is the most common mistake with Decorator Pattern?
What should I learn before this topic?
How can I practice it?
Is Decorator Pattern hard to learn?
How long does it take to learn Decorator Pattern?
Which topics are related to Decorator Pattern?
What should I study after Decorator Pattern?
Related topics
- Strategy Pattern (Software Engineering)
- Dependency Injection (Software Engineering)
- Observer Pattern (Software Engineering)
- MVC Architecture (Software Engineering)
- Producer-Consumer Pattern (Concurrency & Parallelism)
- Saga Pattern (Distributed Systems & Cloud)
- Pattern Matching (Languages & Compilers)