Introduction

The decorator design pattern is a software design pattern that helps you add responsibilities to an object at runtime. This pattern is considered to be a structural design pattern. This type of pattern focuses on the relationships between classes and how they can help solve specific problems.

The Gang of Four, in their book Design Patterns: Elements of Reusable Object-Oriented Software, defined the intent of decorator pattern like this:

Intent:_ Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality._

One of the key characteristics of this design pattern is that it follows the Single Responsibility Principle (SRP). This is because each “decoration” you add to an object, will be encapsulated within a class. This class’s responsibility will be to handle everything related to adding that decoration to that object.


Time to assemble a 🍔

For purposes of learning the decorator pattern, let’s assume you want to create an object of type Hamburger.

How a hamburger is assembled varies. According to Burger King, there are 221,184 possible ways to order a Whopper. It will take you at least 200 years to eat these many hamburgers if you were to eat one hamburger for breakfast, lunch, and dinner! The possibilities are endless.

In a world without the decorator pattern, an approach you might take is to create a parent Hamburger class and then subclasses for the different types of hamburgers. This could easily become a maintenance headache as it will make troubleshooting more difficult due to the complexity of multiple levels of inheritance.

#design-patterns #java #software-engineering #decorator-pattern #programming

Design Patterns — Decorator Design Pattern
2.00 GEEK