Decorator Design Pattern

      No Comments on Decorator Design Pattern

What Is Decorator Pattern?

Decorator design pattern is a pattern which modifies the functionality of an object. In other words it gives different flavours to an object without using inheritance. You might think why not use inheritance if you are talking about flavours? Well, yes these are flavours but the permutation and combination of these flavours can be many and in that case it doesn’t make sense to create a class for each combination.

Lets say you have 6 factors that can change the characteristics of your object, in that case you will have factorial of 6 which is, 6! = 720, so there can be 720 objects with different characteristics.

When to use it?

This pattern can be used when you have a requirement that you have to add characteristics to an object at runtime. And the factors that can affect the object’s characteristics are many.

Video

Lets Understand With An Example..

Problem Statement – In a flight while booking a main cabin seat, you can choose facilities like WiFi, Live TV, Head Phones etc. At the end you should show the price of the seat after including the individual price of each facility that user has chosen. For instance

Main cabin seat – $ 500.0
WiFi: $ 10
Live TV: $ 8.0
Head Phones: $ 5.0

If use choses WiFi and Head Phones with main cabin seat then total cost would be 500.0 + 10.0 + 5.0 = $ 515.0

Similarly there can be multiple combination of facilities a user can choose.

Design

Decorator Design Pattern

As you can see in the above image that we have a FlightSeat Interface and MainCabinSeat implements FlightSeat. We have an abstract class FlightSeatDecorator which holds an instance of FlightSeat. And we have 3 facilities (decorators) which extends the FlightSeatDecorator class.

Implementation

Above is the github link to decorator pattern implementation. Still we will discuss the implementation of some important classes.

The FlightSeat interface has only two methods one gives the chosen facilities with the seat and other tells the cost of the seat with facilities.

The FlightSeatDecorator has an instance of FlightSeat and also has both the methods.

MainCabinSeat implements the FlightSeat and both its methods.

WiFi decorator extends the FlightSeatDecorator and implements both the methods which are there in the decorator. It has its own cost.

Below is the main class which shows how we can use the facilities with the seat and get the cost.

If you want to see the implementation of all the classes then please visit the github link. And if you have any feedback, suggestion, concern or opinion please leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *