Decorator Design Pattern

Get an overview of the decorator design pattern.

Overview

Suppose that we’re in a restaurant and order some beverages from a list (coke, coffee, tea). But along with the different drinks, the restaurant also gives us the option of adding ice and lemon to our beverage (with an additional cost).

One way to program this problem would be to create a base class of beverages and inherit multiple classes like Coke, Coke_lemon, Coke_ice, Coffee, Cold_coffee, and so on. Just by looking at the names of the classes, we can see that there will be a problem if the restaurant wants to add more beverages or add-ons. This will exponentially increase the number of classes.

One way to approach this problem would be to use the bridge pattern, as discussed previously. But there’s a problem: what if we want double ice or lemon in our beverage, or lemon in addition to ice? This is where the bridge pattern fails to solve the problem. Here, the decorator pattern comes to the rescue.

Decorator pattern

Let’s define the decorator design pattern.

The decorator design pattern attaches new behaviors to the objects by placing them inside wrapper objects that contain the behavior. Now, let’s go back to our problem and see how the decorator pattern will solve it.

First, we create a Beverage class that will be inherited by concrete classes Coke, Coffee, and Tea. Then, we create a decorator class, Addon, which will be implemented by concrete decorators Ice and Lemon. The decorator Addon class will have a unique relationship with Beverage. The Addon class behaves like a Beverage (is a relationship), and the Addon has a beverage (has-a relationship). We can refer to the UML diagram under the structure heading at the bottom of this lesson to see all of this.

Now, with this design, we can create a simple instance of Tea, Coffee, or Coke. Or, we can pass the instance of Tea to the Ice class to make an iced tea. Then, we can pass this iced tea instance to the lemon class to make lemon iced tea. In essence, we can create any combination of beverages with the add-ons without creating a lot of classes.

Get hands-on with 1200+ tech skills courses.