Wednesday, March 30, 2022

SKP's GoF Design Patterns a Day - 06 - Template

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-pattaya

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


Template Pattern [Sample Code]
Imagine a real-world scenario where a factory is creating both aluminium nails and screws. Though the machine has to create both of them through similar processes, the way some steps are implemented may vary in each of these. When we think of such scenarios in software, we utilize the template pattern. Template pattern defines a way to re-use algorithms for various implementations with different or slightly different outcomes.
 
Fig. 4 : Template (Structural) Design Pattern - Sequence Diagram 
[Source : Wikipedia]


In the attached example, the abstract class SoftwareProcessor defines a general set of algorithmic steps (functions) to deliverSoftware(). This class is my template class. Since the implementation and testing phases differ in projects based on the technology stack being used, CProcessor and JavaProcessor classes adapt this algorithm for these phases. The common methods are all implemented in SoftwareProcessor and the specific ones are left as abstract.

SoftwareConsultants can be used to run this example. Try adding your own processor.

No comments: