Template Method Example

Learn about the template method with coding examples.

We'll cover the following

Example

Let’s look at the code of the example we discussed in the previous lesson. We have a MlModel base class that defines a template method applyAlgo(). It has three steps:

  • readData()
  • writeData()
  • trainModel()

The first two are common to any machine learning model and are implemented in the base class itself. The trainModel() method can be implemented in different ways, so it is declared abstract in the base class. This does not stop us from defining applyAlgo() as a template method.

We also have LinearRegression and Ann classes that are derived from the MlModel class and are meant to implement the corresponding machine learning algorithms. The client can instantiate a derived class using the base class pointer. Calling the applyAlgo() method on the object will invoke the corresponding implementation.

Get hands-on with 1400+ tech skills courses.