0

Template Pattern

The Template Method pattern is known as a¬†behavioural¬†pattern, as it’s used to execute an algorithm and it can provide default implementation that might be common for all or some of the subclasses. It provides a template for the concrete class. The definition of Template Method provided in the original Gang of Four books on DesignPatterns states:

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.

Example: Email Template.

Source Code (Java):

public abstract class EmailTemplate {
	
	public String emailHeader = "Email Header";
	public String emailFooter = "Email Footer";
	
	abstract String emailBody();
}public class NewYearEmail extends EmailTemplate{

	@Override
	String emailBody() {
		// TODO Auto-generated method stub
		return "This is New Year Email";	
	}
}
public class MainClass {
	
	public static void main(String[] args){
		
		NewYearEmail newYearEmail = new NewYearEmail();
		System.out.println("Email Header : " + newYearEmail.emailHeader);
		System.out.println("Email Body : " + newYearEmail.emailBody());
		System.out.println("Email Footer : " + newYearEmail.emailFooter);
	}
}

Toufiq Mahmud

Leave a Reply

Your email address will not be published.