Decorator Pattern

A decorator pattern allows you to dynamically attach additional behaviors to an individual object. The additional behaviors will be wrapped around the object to give it additional attributes.

If you use inheritance to accomplish the same task without the decorator pattern, then a large code would have too many subclasses to be able easily maintain. Imagine programming software for a pizza shop. Every pizza has a crust, cheese, and sauce. Sure, all the different kinds of pizzas can inherent from the simple pizza, but this will create many subclasses and will cause a nightmare code and maintain after awhile. By wrapping the extra toppings class around the pizza object, you can get any combination of toppings on a pizza without making a subclass for every combination of the pizzas with various toppings.

The Design of the Decorator Pattern

Since I have been talking about a pizza shop, I will continue with that theme. In this example, I will have a simple pizza object and have all the toppings wrap around the object so the description and cost will be updated as needed.

 Here is my UML diagram.




















As you can see, I have interfaces called Pizza and TheToppings. You can use abstract classes if your code calls for it. I used a common interface so the toppings and the pizza object can relate to each other.

I also have concrete classes that will take care of the cost description, and any other functions that we need them to do.

The Code

Lets get into the interfaces. They are straightforward.


The pizza interface:



And the toppings interface:



Now, here are the concrete classes

The simple pizza that will be the main object:



Then the toppings that make each pizza unique:



The main code.


The Output:

Here what I got for the final output.


Final Note

Overall, the Decorator Pattern can help with the number of classes that it will take to accomplish a task but the possible drawback of this pattern is having too many small similar classes. For a pizza shop, this pattern can help but a situation where you have to program for a factory that builds heavy machinery, this pattern will not work because of the number of parts that is required to build the product.