Design Pattern Basic Tutorial

adplus-dvertising
Template Method
Previous Home Next

The Template pattern Provide a feature for class or method that is abstract definition. with the help of these feature we can redefine the behavior of the class or method without changing in its structure.

Benefit and use of Template Pattern
  1. The Template Pattern is used to make more than one similar operations template.
  2. From many specialized operations to a generalized operation.
  3. It is Refactor common behavior in simplify code.
  4. It is provide the related Algorithm for improvement.
  5. For conquer it Need good coding skill.
  6. It May be hard to read for novice.
  7. Easy to produce ambiguity if not written well.

We can write the code Without using template method pattern, but when you write without template then you may write more lines of code. With the use of the design pattern we don't have any side effect and we don't need to cast in or out.

Example


package r4r;
abstract class CheckBackup {
 public abstract void checkBankAccount();
public abstract void checkCreditCard();
public abstract void checkLoanApplication();
public abstract void checkStockAccount();
public abstract void checkIncometax();

  //work as template method Pattern
public void checkList() {
checkBankAccount();
checkCreditCard();
checkLoanApplication();
checkStockAccount();
checkIncometax(); 
}
}

class LoanApplication extends CheckBackup {
private String name;
   
public LoanApplication(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void checkBankAccount() {
   
System.out.println("check bank account...");
}

public void checkCreditCard() {

System.out.println("check credit Card...");
}

public void checkLoanApplication() {
   
System.out.println("check other loan application...");
}

public void checkStockAccount() {
   
System.out.println("check stock values...");
}

public void checkIncometax() {

System.out.println("check income tax...");
}
   
//other methods
}
public class templatetest {
public static void main(String[] args) {

LoanApplication la = new LoanApplication("john");
System.out.println("\nCheck client " + 
	la.getName()+ " loan application. ");
la.checkList();

LoanApplication equityClient = new LoanApplication("tommy");
System.out.println("\nCheck client " + 
	equityClient.getName()+ " loan application. ");
equityClient.checkList();
}
}

Previous Home Next