Friday, August 25, 2023

The Template Method Design Pattern...

 It is a behavioral design pattern. It lets us define the skeleton of an algorithm, delegating some steps to the subclasses.

There are mainly two participants in this design pattern

- AbstractClass : It defines the abstract primitive methods that the subclasses will override. It also implements a template method which define the algorithm.

- ConcreteClass : it implements the abstract primitive methods of the Abstract Class.

Let us try to understand this design pattern from an example.

Suppose we are modeling the daily activity of an engineering student in college.

All students need to sign in and sign out in a common register. So these common tasks are part of the Base class.

However, each student has to attend the classes of his own stream - maybe Electronics, Computer Science, Mechanicals, etc.

So this part of the basic activity depends on the stream of the student and constitutes part of the Concrete class.

The UML diagram of the code is as follows:



Here is the source code of the Template Method Design Pattern

from abc import ABC, abstractmethod

class EngineeringStudent(ABC):
def __init__(self):
pass
def signIn(self):
print("\n Start of the day. I need to sign in the common register")
def signOut(self):
print("\n End of the day. I need to sign out in the common register")
@abstractmethod
def attendClass(self):
pass
def activityofAStudent(self):
self.signIn()
self.attendClass()
self.signOut()

class ElectronicsStudent(EngineeringStudent):

def __init__(self):
print("\n I am an Electronics Student")

def attendClass(self):
print("\n Attend the classes in the Electronics dept")

class ComputerScienceStudent(EngineeringStudent):
def __init__(self):
print("\n I am a CS Student")
def attendClass(self):
print("\n Attend the classes in the CS dept")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
electronicsStudent = ElectronicsStudent()
electronicsStudent.activityofAStudent()
csStudent = ComputerScienceStudent()
csStudent.activityofAStudent()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

If we run the above program, the output will be as follows:


 I am an Electronics Student


 Start of the day. I need to  sign in the common register


 Attend the classes in the Electronics dept


 End of the day. I need to sign out in the common register


 I am a CS Student


 Start of the day. I need to  sign in the common register


 Attend the classes in the CS dept


 End of the day. I need to sign out in the common register


No comments: