in Programming in C
311 views
0 votes
0 votes

Imagine a scenario where new child classes are introduced frequently from a base class. The method calling sequences for every child class are the same but the implementations are different among the child classes. Here which design pattern would you like to apply? Explain the reasons with examples j

in Programming in C
311 views

1 Answer

0 votes
0 votes

In this scenario, it sounds like the Template Method design pattern would be a good fit. This pattern defines the skeleton of an algorithm in a base class, with certain steps defined as abstract methods. Subclasses can then override these methods to provide their own implementation for each step. This allows for the common method calling sequence to be defined in the base class, while still allowing for flexibility in the implementation of each step for each child class.

Here's an example of how the Template Method pattern could be implemented in Python:

from abc import ABC, abstractmethod

class BaseClass(ABC):
    def template_method(self):
        self.step_one()
        self.step_two()
        self.step_three()
    
    @abstractmethod
    def step_one(self):
        pass
    
    @abstractmethod
    def step_two(self):
        pass
    
    @abstractmethod
    def step_three(self):
        pass

class ChildClassOne(BaseClass):
    def step_one(self):
        print("ChildClassOne: step one")
    
    def step_two(self):
        print("ChildClassOne: step two")
    
    def step_three(self):
        print("ChildClassOne: step three")

class ChildClassTwo(BaseClass):
    def step_one(self):
        print("ChildClassTwo: step one")
    
    def step_two(self):
        print("ChildClassTwo: step two")
    
    def step_three(self):
        print("ChildClassTwo: step three")

child_one = ChildClassOne()
child_one.template_method()
# Output: "ChildClassOne: step one", "ChildClassOne: step two", "ChildClassOne: step three"

child_two = ChildClassTwo()
child_two.template_method()
# Output: "ChildClassTwo: step one", "ChildClassTwo: step two", "ChildClassTwo: step three"

In this example, the BaseClass defines the template_method which calls the three abstract methods step_one, step_two, and step_three. The ChildClassOne and ChildClassTwo classes both inherit from BaseClass and provide their own implementation for each of these methods. When the template_method is called on an instance of either ChildClassOne or ChildClassTwo, the common sequence of method calls is preserved, but the implementation of each step is specific to the child class.

Related questions