Tuesday, 19 April 2016

Template pattern - Example


A Loan application process may take several steps to finish.
Let's assume the steps are as follows : 
  • Check client's bank balance history
  • Check client's credit score from three different companies
  • Check client's other loan information
  • Check client's stock holding value
  • Check client's income potential in the future etc.
You may use a template method to hold the process steps together without considering the real implementation in the subclass.

abstract class CheckBackground { 
    public abstract void checkBank();
    public abstract void checkCredit();
    public abstract void checkLoan();
    public abstract void checkStock();
    public abstract void checkIncome();

    // work as template method
    public void check() {
        checkBank();
        checkCredit();
        checkLoan();
        checkStock();
        checkIncome();
    }
}

class LoanApp extends CheckBackground {
    private String name;

    public LoanApp(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    public void checkBank() {
        // check acct, balance
        System.out.println("check bank...");
    }
    public void checkCredit() {
        // check score from 3 companies
        System.out.println("check credit...");
    }
    public void checkLoan() {
        // check other loan info
        System.out.println("check other loan...");
    }
    public void checkStock() {
        // check how many stock values
        System.out.println("check stock values...");
    }
    public void checkIncome() {
        // check how much a family make
        System.out.println("check family income...");
    }
    //other methods
}

class TestTemplate {
    public static void main(String[] args) {       
        LoanApp mortgageClient = new LoanApp("Judy");
        System.out.println("\nCheck client " + 
          mortgageClient.getName()+ " Mortgage loan application. ");
        mortgageClient.check();
        
        LoanApp equityloanClient = new LoanApp("Mark");
        System.out.println("\nCheck client " + 
          equityloanClient.getName()+ " equity loan application. ");
        equityloanClient.check();
    }
}


Method overloading and method overriding are good examples of template method pattern.

For example,
Coercion polymorphism -- refers to a single operation serving several types through implicit type conversion.

Overloading polymorphism -- refers to using a single identifier for different operations.

Parametric polymorphism -- refers to a class declaration that allows the same field names and method signatures to associate with a different type in each instance of that class.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.