Decorator Design Pattern

Nipun Arora
Design Patterns with Python
2 min readSep 19, 2018

Moving on with our series on Design Patterns with Python , The pattern in focus today is the Decorator Design Pattern. Basically with this pattern we generally wrap objects/functions(For languages where in functions are not treated as objects) with more functionality and lesser code redundancy.We will be able to understand this better with the help of an example.

Before we begin with the example, some of you might be thinking that this extension behaviour can be achieved using inheritance as well then why do we need this pattern, we will be discussing this at the end of the article once we see what exactly the decorator pattern is.

Decorating a person object 😜

Now coming to our example lets consider we are writing a web application where in to access few secured pages on the site you need to be logged in, thus before displaying these pages to the user we need to check if the user is logged in(may be done using sessions and cookies, the implementation is not of our interest right now)

Access Provided only after security check 😜

As a naive programmer you might write a check snippet in every such view of the web app , which checks whether the user is logged in or not if not prompts him to login. Somewhat like this…… 🤔

Now suppose we have hundreds of such pages which are available only to logged in users ,writing this check for login within each view increases the code redundancy.

Thus, we create a decorator as shown below to save us the redundancy

A similar example could be the the results we would like to cache in a web app, the methods retrieving those results can be decorated with cache saving decorator.

In General, A Decorator Pattern is useful in the following cases

  • Enhancing the response of a component as it sends data to a second component
  • Supporting multiple optional behaviours

Now coming to the inheritance vs decorator debate, It is usually claimed that inheritance provides compile time inheritance and decorators provide run-time extension but all this ultimately boils down to which of the two,Help you lower your code complexity. In the above example, had we created a subclass for all the view classes which only permits logged in users the code complexity would have surely gone up !

Well that is it for this design pattern. 😆

Open to all kinds of doubts/suggestions in the response below.

--

--

Nipun Arora
Design Patterns with Python

Android and Full Stack Backend Developer ,frolicking in the fascinating world of apps.