The Decorator Pattern in 3 Minutes

Emanuel Trandafir
Javarevisited
Published in
4 min readApr 24, 2023

--

Let’s dive into the fascinating world of decorators.

The scuba diving suit is a good example of the decorator pattern: It allows the diver to breathe underwater by making the “breath()” method use a different supplier of Oxygen. Photo by Sebastian Pena Lambarri on Unsplash

Overview

The Decorator pattern is a structural design pattern in object-oriented programming that allows you to dynamically add behavior to an object without changing its class.

It involves creating a decorator class that wraps the original object and provides additional functionality by adding new methods or modifying existing ones. The decorator class implements the same interface as the original object, so the client code can use it transparently.

The Decorator pattern is useful when you need to add functionality to objects at runtime or when it’s not feasible to extend them using inheritance. It allows you to avoid creating a large number of subclasses to handle different combinations of behaviors, which can lead to code duplication and maintenance issues.

Instead, you can create small, focused decorator classes that add specific features to the base object. The Decorator pattern promotes the Open-Closed Principle, which states that classes should be open for extension but closed for modification

The Problem

Let’s consider we are using an interface to interact with the database for fetching account information based on username:

--

--

Emanuel Trandafir
Javarevisited

Hi, I'm Emanuel Trandafir, a Java developer from Romania. I have a strong passion for clean code, software design, and unit testing.