A guide to software design patterns

Structural Design Pattern: Decorator

Peterson C
The Startup
4 min readMar 19, 2020

--

Photo by Kamil S on Unsplash

The decorator pattern, one of the seven structural patterns, allows behavior to be added to an individual object, dynamically, without modifying the behavior of other objects from the same class.

The implementation of this pattern is also a good example of the single responsibility principle (S) of the S.O.L.I.D principles. It’s also very similar to the Chain Of Responsibility pattern with one major difference. In this pattern, all the classes handle the request while only one class handles the request in the chain of responsibility.

I’ve always found it easier to understand any new concept with a real-world scenario. Let’s use a real scenario and implement it using the decorator pattern.

Let’s say you work for a video game company and are tasked to create a character module. Because you will be working in parallel with another team, they request just the contract for now and will inject characters in their code as needed. A character should be able to display their available attacks. There is a basic character, which is the starting character, and as you level up in the game, characters also level up with additional attacks. Let’s see what that would look like in code.

--

--

Peterson C
The Startup

Husband, father, engineer, musician, and writer by luck. I write mostly about whatever comes to mind. Follow me on this crazy writing journey if you dare.