As per Wiki structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships among entities. In this post we will discuss Decorators.
Decorators, add additional features to object dynamically without using sub-classing
Let’s consider an analogy here, our bakery needs some automation, everyday I spend few hours setting up appliances like pre-heating the oven, setting kitchen temperature, cleaning utensils this consumes a lot of my time, I could spend that time in creating new dishes, how can I automate this, without employing extra hands?
I have been hearing about this Internet of things a lot lately, I think this is what I need. So I made an app that get readings from all my devices, the functions of this app is:
- Set temperature for kitchen
- Set temperature for oven
- Turn on the Dishwasher
- Turn off Oven
- Turn off Dishwasher
- Send Notification in case of Fire/ Burglary

So this inheritance model works just fine, but the issue is what if I have to do multiple things together? Like Set temperature for both oven and thermostat, or turn off all appliances. In such a case Inheritance wold not be solution, reason being:
- Inheritance is not Dynamic, you will not be able to change the behavior of object at run-time
- Multiple inheritance, most languages doesn’t support it.
- Tightly coupled (Coupling and Cohesion)
Solution to this problem would be object that could be linked to our object, This can be refereed to as a Wrapper or Decorator.
Below is an implementation of how decorator works.
from datetime import datetime
from functools import wraps
def turn_on_appliances(function):
""" Defines this decorator """
@wraps(function)
def decorator():
appliance_status = 'Off'
""" Takes the return value of the function being decorated """
value = function()
if datetime.now().hour <= 10:
appliance_status = 'On'
status = "The status the appliance is --> {}".format(appliance_status)
return status
return decorator
@turn_on_appliances
def appliance_status_function():
"""Original Function """
return ("Status of appliance")
#Check the result of decorating
print(appliance_status_function())
#Check if the function name is still the same name of the function being decorated
print(appliance_status_function.__name__)
#Check if the docstring is still the same as that of the function being decorated
print(appliance_status_function.__doc__)
Hope this was useful stay tuned for more on Structural Design Patterns.
Leave a comment