DEV Community

Somenath Mukhopadhyay
Somenath Mukhopadhyay

Posted on

Decorator Design Pattern in Python

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

What problems can it solve?

- Responsibilities should be added to (and removed from) an object dynamically at run-time

- A flexible alternative to subclassing for extending functionality should be provided.

When using subclassing, different subclasses extend a class in different ways. But an extension is bound to the class at compile-time and can't be changed at run-time.

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class.

This is achieved by designing a new Decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:

Subclass the original Component class into a Decorator class (see UML diagram);

- In the Decorator class (SpecialistTeacher), add a Component reference as an attribute;

- In the Decorator class, pass a Component to the Decorator constructor to initialize the Component attribute;

- In the Decorator class, forward all Component methods to the Component pointer; and

- In the ConcreteDecorator class (specialistMathTeacher, specialistChemistryTeacher, etc), override any Component method(s) whose behavior needs to be modified.

This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).

Note that decorators and the original class object share a common set of features. In the UML diagram, the doWork() and calculateSalary() methods were available in both the decorated and undecorated versions.

Here is the source code of the Decorator Design Pattern in Python:

from abc import ABC, abstractmethod

class Teacher(ABC):
    @abstractmethod
    def calculate_salary(self):
        pass

    @abstractmethod
    def do_work(self):
        pass

class BasicTeacher(Teacher):
    def __init__(self, base_salary: int):
        self.base_salary = base_salary

    def calculate_salary(self):
        return self.base_salary

    def do_work(self):
        print("I am a basic teacher. I do general teaching work.")

## Decorator
class SpecialistTeacher(Teacher):
    def __init__(self, teacher: Teacher):
        self.teacher = teacher

    def calculate_salary(self):
        return self.teacher.calculate_salary()

    def do_work(self):
        self.teacher.do_work()

class SpecialistPhysicsTeacher(SpecialistTeacher):
    def __init__(self, teacher: Teacher):
        super().__init__(teacher)

    def calculate_salary(self):
        return super().calculate_salary() + 8000

    def do_work(self):
        super().do_work()
        print("I am a specialist Physics Teacher. I teach Physics.")

class SpecialistMathsTeacher(SpecialistTeacher):
    def __init__(self, teacher: Teacher):
        super().__init__(teacher)

    def calculate_salary(self):
        return super().calculate_salary() + 10000

    def do_work(self):
        super().do_work()
        print("I am a specialist Maths Teacher. I teach Maths.")

class SpecialistChemistryTeacher(SpecialistTeacher):
    def __init__(self, teacher: Teacher):
        super().__init__(teacher)

    def calculate_salary(self):
        return super().calculate_salary() + 7000

    def do_work(self):
        super().do_work()
        print("I am a specialist Chemistry Teacher. I teach Chemistry.")

if __name__ == '__main__':
    # Creating a physics teacher with a base salary of 10000
    specialist_phy_teacher = SpecialistPhysicsTeacher(BasicTeacher(10000))
    specialist_phy_teacher.do_work()
    print(f"My Salary is {specialist_phy_teacher.calculate_salary()}")

    # Creating a teacher who is a specialist in both Physics and Maths
    specialist_phy_maths_teacher = SpecialistMathsTeacher(SpecialistPhysicsTeacher(BasicTeacher(10000)))
    specialist_phy_maths_teacher.do_work()
    print(f"My Salary is {specialist_phy_maths_teacher.calculate_salary()}")
Enter fullscreen mode Exit fullscreen mode

If we run the above program, the output will look like the following:

I am a specialist Physics Teacher. I teach Physics

My Salary is 18000

I am a specialist Physics Teacher. I teach Physics

I am a specialist Maths Teacher. I teach Maths

My Salary is 28000

Top comments (0)