Template Method

Template Method Java Design Pattern Tutorial
Template Method : defines the skeleton of an algorithm in an operation deferring some steps to subclasses. Template method lets subclasses refine certain steps of an algorithm without changing the algorithm’s structure.

Example

Account.java
package com.templatemethodpattern.example;

public abstract class Account {
 
 public final void openAccount() {
  collectCustomerDetails();
  verifyCustomerDetails();
  saveCustomerDetails();
  //using hook
  if (isCustomerPreferedAccountType()) {
   setAccountType();
  }

 }
 
 public abstract boolean isCustomerPreferedAccountType();

 public void setAccountType() {
  System.out.println("Setting AccountType to default Saving Account");

 }

 public final void collectCustomerDetails() {
  System.out.println("Customer Details are collected for Account Opening");

 }

 public final void verifyCustomerDetails() {
  System.out.println("Customer Details are verified");

 }

 public final void saveCustomerDetails() {
  System.out.println("Customer Details are now Saved");

 }

}
DefaultSavingsAccount.java
package com.templatemethodpattern.example;

public class DefaultSavingsAccount extends Account{


 @Override
 public boolean isCustomerPreferedAccountType() {
  return false;
 }

}
CustomerPrefSavingsAccount.java
package com.templatemethodpattern.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CustomerPrefSavingsAccount extends Account {

 public void setAccountType() {
  System.out.println("Setting Account Type to Elite Saving Account");
  
 }

 @Override
 public boolean isCustomerPreferedAccountType() {
  String answer = getUserInput();
  if (answer.toLowerCase().startsWith("y")) {
   return true;
  } else {
   return false;
  }
 }
 
 private String getUserInput() {
  String answer = null;
  System.out.println("would you like to have Elite Savings Account (y/n) ?");
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

  try {
   answer = in.readLine();
  } catch (IOException e) {
   System.out.println("IO error while reading your answer");
  }
  if (answer == null) {
   return "no";
  }
  return answer;
 }

}
AccountTestDrive.java
package com.templatemethodpattern.example;

public class AccountTestDrive {
 
 public static void main(String[] args) {
  Account defaultSavingsAccount = new DefaultSavingsAccount();
  defaultSavingsAccount.openAccount();
  System.out.println("-----------------------------------------");
  
  /* Using Hook : isCustomerPreferedAccountType method to get the user
   Preference and set the Customer AccountType accordingly*/
  Account eliteSavingsAccount = new CustomerPrefSavingsAccount();
  eliteSavingsAccount.openAccount();

 }
}




Home

No comments:

Post a Comment