This is the third post in a series about design patterns. I decided to make a dating profile for each pattern as a way to remember the various patterns, because I’m always mixing them up. This series is not meant to be a deep dive into the patterns and how to implement them (there are many posts on that topic already) but is meant to provide a high level understanding.
The Decorator pattern is a powerful alternative to subclassing. By using the decorator pattern, you can add behavior and responsibilities to individual objects at runtime where subclassing adds behavior to all instances of a class at compile time. Using the Decorator pattern is like wrapping a gift, putting it in a box, and wrapping the box. Both the Decorator and the core object share the same interface and the Decorator wraps around the core object using composition. One drawback to the Decorator pattern is that the core object’s identity is hidden and trying to access the core object directly is problematic.
Makeover
Changing objects' appearance is a common example given for the Decorator pattern. If you’re creating a custom GUI, you can create a display element like a window and decorate it with classes to add a border, a background, give it the correct vertical or horizontal scroll, or any combination therein. If you are implementing the ability to draw a shape, you can similarly use the Decorator pattern to give it a fill, border, and opacity among other properties not inherent to the definition of the shape itself.
If the Decorator pattern were a person, they would definitely be the type of person who loves to makeover their partner and go shopping for a whole new wardrobe. The Decorator pattern has a specific look in mind and will make sure their partner gets the right clothing, shoes, and haircut.
Change is hard
The Decorator pattern is used to add behavior and responsibilities to an object that are not inherent to its identity. For example, a pizza is still a pizza whether it has pineapple on it or not, red sauce or white sauce, or whether the crust is gluten-free and cauliflower or gluten-full and full of flour. But as you decorate an object more and more, accessing it’s core identity is a problem. Think of all the different kinds of crusts, sauces, and toppings you can get for a pizza now. Some of the pizza toppings that are becoming trendy are truly wild, shrimp, fried egg, guacamole, french fries, Oreos, or even chicken tikka masala. How do you define what makes a pizza now?
The Decorator pattern is the person that wants to change their partner. Beyond their appearance, the Decorator pattern wants to change your neighborhood, your hobbies, your diet, and your fitness routine. They push you to become the rock-climbing vegetarian who rents an apartment in Logan Square if that’s what they’re into this month. Be careful with the Decorator pattern, or you won’t recognize yourself.