Advertisment

Template Method

author-image
CIOL Bureau
Updated On
New Update

Avijeet

Dash
, Satyabrata

Dash
, Shashidhara

S G

Advertisment

Template Methods lead to an inverted control structure that’s sometimes

referred to as "the Hollywood principle", that is, "Don’t call

us, we’ll call you". This refers to how a parent class calls the

operations of a subclass and not the other way round. Template methods are so

fundamental that they can be found in almost every abstract class.

Intent

Advertisment

Define the skeleton of an algorithm in an operation,

deferring some steps to client subclasses. Template Method lets subclasses

redefine certain steps of an algorithm without changing the algorithm's

structure.

 

Advertisment

In 30 Seconds

Advertisment

The catch here is "how a parent class can enforce an

invariant for its subclasses
". Algorithms often have invariant parts

and variant parts. Now, the idea here is to implement all the invariant and

variant parts once in the parent class and let subclasses implement their own

variant parts. The critical thing about the Template method is it fixes the

ordering of the steps of an algorithm.

The step’s implementation can vary depending on the

subclass. Some steps can be implemented in the abstract methods in the parent

class. Some steps can be "Hook" methods, which do nothing in parent

class but may get overridden by subclass. Basically the steps are like primitive

operations some of which must get overridden and some may not. The idea is to

factor and localize the common behavior among subclasses in a Template method

and keep it in the parent class. This pattern is the target of the rafactoring

called "form template method".

Advertisment

Motivation

From an object collaboration angle we have an Abstract class

and concrete classes. The Abstract class has the one and the only Template

method, which calls primitive operations in it. The primitive operations are

abstract methods in the abstract class, which may get overridden in the concrete

class.

Advertisment

 

Template Method is used prominently in frameworks. Each

framework implements the invariant pieces of a domain's architecture, and

defines "placeholders" for all necessary or interesting client

customization options. In so doing, the framework becomes the "center of

the universe", and the client customizations are simply "the third

rock from the sun". This inverted control structure has been affectionately

labeled "the Hollywood principle" - "don't call us, we'll call

you".

 

Advertisment

For example the standard template library, used extensively

in C++ programs, makes use of this pattern. The std::map is a best example for

this. In this template class the library provides the flexibility of redefining

the compare method of the class, which is used inside almost all the operations

of the class. This allows the user to use even the user defined structures as

keys inside the map and he can provide the corresponding comparison method for

that structure.

 

The Template Method defines a skeleton of an algorithm in an

operation, and defers some steps to subclasses. Let us take the example of Loan

accounts, where it is required to calculate the interest on different loan

accounts. The interest rate and the type of the interest (may simple interest or

compound interest) may be different for different types of accounts.






Structure

Example

Here we have an algorithm Calculate Interest defined

in the base class LoanAccount that uses two primitive operations inside

it.

  1. GetInterestType
  2. GetInterestRate

CalculateInterest is the Template Method. The method

provides the flexibility for the subclasses to decide the type of the interest

that is going to be used, and also the rate of interest rate to be used, which

obviously differs for different loan accounts.






Sample Code

abstract class LoanAccount{
        //the template method — which is not overridden
        public void calculateInterest(){
	      // Get Interest Rate
             double interest=getInterestRate();
             char intType=getInterestType();
             /* Algorithm to calculate interest can be implemented here
        */
             }
	   protected double abstract getInterestRate();
	   protected char abstract getInterestType();
}
class AccountA extends LoanAccount{
	   public double getInterestRate{
		     return 10.0;
	   }
	   public char getInterestType(){
		     //return Simple
		     return ‘s’;
	  }
}
class AccountB extends LoanAccount{
	   public double getInterestRate{
	         return s.0;
	   }
	   public char getInterestType(){
		     //return Compound
		     return ‘c’;
      }
}

// Client class
public class Client{
	  public static void main(String args<>){
           //client knows the kind of subclass to use, and the
           subclass calls the parent       //class’s template method
           LoanAccount account=new AccountA();
		    account.calculateInterest();
	  }
}



Complexities simplified

Template Methods call the following kinds of operations

    1. Concrete operations(either on ConcreteClass or on client classes)
    2. concrete AbstractClass operations(i.e. operations that are generally

      useful to subclasses)
    3. primitive operations(i.e. abstract operations). getInterestType() and

      getInterestRate() are primitive operations.
    4. factory methods.
    5. hook operations, which provide default behaviors that subclasses can

      extend if necessary.
  • There can be any number of templateMethods (calculateInterest() is a

    template method in the above example), each of which can call any number of

    primitive operations.
  • There can be any number of ConcreteClass subclasses of AbstractClass. The

    primitive operations are often (but not always) abstract methods of the

    AbstractClass, and they should be protected.

The templateMethods are not overridden by subclasses while the

primitive operations are overridden.

Related Patterns

Factory Methods are often called by template methods.

Strategy: Template methods use inheritance to vary part of an algorithm.

Strategy uses delegation to vary the entire algorithm.

(The authors are working as Senior Developers at MindTree

Consulting Pvt. Ltd.)

tech-news