The decorator pattern is used to “decorate” or extend objects with added functionality at run-time. This gives developers the ability to compose objects that are purpose driven for the current demands of their users.
In the blog post How the Decorator Pattern Saved My Day on CodeFX, Nicolai Parlog gives a real life example of how the decorator pattern was useful. He describes a scenario that involves a UI that triggers many different responses depending on the user’s interaction with it. However, different panes may have slightly different responses or needs. He then describes several different ways to implement this:
- Using one class which activates and deactivates different responses with flags
- Using inheritance
- Using the decorator pattern
In the first scenario you would end up with a behemoth of a class that would be hard to write, test, understand, and modify.
The second scenario is a better solution than the first one, however all it did was simulate flexibility, making it seem like you can pick and choose but you couldn’t. When he was trying to replace JEditorPane with FX’ WebView, he realized that WebView automatically triggered some of the responses that were implemented in the second scenario. This caused the whole system of classes to collapse. So he refactored the previous implementation to use the decorator pattern, replacing the original classes with the right combination of decorators. By using decorators instead of inheritance, the classes are easier to understand, it’s easier to test because there are fewer things happening in each unit, and it made the code reader for future changes. Instead of having to figure out where to put new functionality, all you need to do is create a decorator and add it where it’s needed.
The reason I chose this blog is because I have an assignment coming up on this particular design pattern and I didn’t really know what the decorator pattern was and what it was used for in a real world scenario. So I went to search for an example. This blog helped me understand when the pattern should be used and the benefits of using it over other methods like inheritance. It also reminded me that just because you’re using a pattern doesn’t mean that your code is going to be cleaner or more efficient, but that you have to remember to only use it when necessary, which you can only do if you understand it.
Source: https://blog.codefx.org/design/patterns/decorator-pattern-saved-my-day/
From the blog CS@Worcester – Andy Pham by apham1 and used with permission of the author. All other rights reserved by the author.