Derek Banas has a youtube channel dedicated to java tutorials and higher level software development concepts. In his video series of design patterns, he describes the value and how to use the Decorator Design Pattern. Banas begins his tutorial by explaining the utilization of the decorator pattern, and then applies it by using a simple example based on a pizza making simulator.
The purpose and value of using the decorator pattern according to Banas is it allows you to dynamically modify an object, without having to hard code additional features. By extension, this allows us to add to old code without having to rewrite the program. Banas suggests to use the decorator pattern in situations where we would want to use inheritance, but where the classes need to be flexible enough to add features to during run time, so inheritance itself is not sufficient. By applying this pattern we are able to favor composition over inheritance.
Banas applies this pattern in an example of a program used to add toppings to a pizza, and display a description and cost. He first implements the solution to this problem using inheritance, hard coding each type of pizza subclass with a preset description and price. However, Banas notes how by using inheritance, we would have to implement an infinite amount of subclasses for each combination of topping. Furthermore, the change in price of a topping would necessitate changing every subclass using that topping. So regular inheritance is not sufficient for this program.
From here out Banas implements the decorator pattern using a Pizza interface, a ToppingDecorator abstract class with a Pizza instance variable, and PlainPizza concrete class. By creating topping classes that extend ToppingDecorator, he is able to add toppings dynamically to a PlainPizza object, calling a string of constructors for each topping (Pizza myPizza = new TomatoSauce(new Mozzarella)…).
I highly recommend Derek Banas’ youtube channel, as he is adept at breaking down high level software design strategies into simple examples anybody can understand, and he is skilled at illuminating the benefits of design patterns over more basic, intuitive implementations. The structure of his videos are easy to follow as well, starting with a high level discussion, moving down to a UML diagram, and finally implementing the solution. This strategy is very helpful for anyone learning or needing clarification on design patterns.
From the blog CS@Worcester – Bit by Bit by rdentremont58 and used with permission of the author. All other rights reserved by the author.