JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Template Method
  • You use the Template Method design pattern when you’ve got an
    algorithm of several steps and you want to allow customization by subclasses.
  • It’s that easy. Implement the steps in that algorithm as an overridable
    method calls in an abstract class, and let the subclasses override
    those steps as required.
  • The Template Method pattern is great when you have a multi-step algorithm
    to implement that you also want to customize
  • Sub classes cant change the sequence of algorithm.
Purpose
  • Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
  • Template Method lets subclasses redefine certain steps of an algorithm without changing
    the algorithm's structure

Applications

  • To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
  • When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.
  • You first identify the differences in the existing code and then separate the differences into new
    operations.
  •  Finally, you replace the differing code with a template method that calls one of these new operations.
  • To control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.
Examples of Template Pattern

  • The Template Method defines a skeleton of an algorithm in an operation, and
    defers some steps to subclasses.
  •  Home builders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number developing a new subdivision. 
  • A typical subdivision consists of a limited number of floor plans with different variations available for each. Within a floor plan, 
  • The foundation, framing, plumbing, and wiring will be identical for each house.
  • Variation is introduced in the later stages of construction to produce a wider
    variety of models.

AutomotiveRobot.java
package com.customize;

import com.template.RobotTemplate;

public class AutomotiveRobot
 
extends RobotTemplate {
  private String name;

  public AutomotiveRobot(String n) {
    name = n;
  }

  public void getParts() {
    System.out.println("Getting a carburetor....");
  }

  public void assemble() {
    System.out.println("Installing the carburetor....");
  }

  public void test() {
    System.out.println("Revolving the engine....");
  }

  public String getName() {
    return name;
  }
}

CookieRobot.java
package com.customize;

import com.template.RobotTemplate;

public class CookieRobot extends RobotTemplate {
  private String name;

  public CookieRobot(String n) {
    name = n;
  }

  public void getParts() {
    System.out.println("Getting flour and sugar....");
  }

  public void assemble() {
    System.out.println("Baking a cookie....");
  }

  public void test() {
    System.out.println("Crunching a cookie....");
  }

  public String getName() {
    return name;
  }
}

RobotTemplate.java
package com.template;

public abstract class RobotTemplate {
  public final void go() {
    start();
    getParts();
    assemble();
    test();
    stop();
  }

  public void start() {
    System.out.println("Starting....");
  }

  public void getParts() {
    System.out.println("Getting parts....");
  }

  public void assemble() {
    System.out.println("Assembling....");
  }

  public void test() {
    System.out.println("Testing....");
  }

  public void stop() {
    System.out.println("Stopping....");
  }
}

TestTemplate.java
package com.test;

import com.customize.AutomotiveRobot;
import com.customize.CookieRobot;

public class TestTemplate {
  public static void main(String args[]) {
    AutomotiveRobot automotiveRobot = new AutomotiveRobot(
        "Automotive Robot");
    CookieRobot cookieRobot = new CookieRobot("Cookie Robot");
    System.out.println(automotiveRobot.getName() ":");
    automotiveRobot.go();
    System.out.println();
    System.out.println(cookieRobot.getName() ":");
    cookieRobot.go();
  }
}

Output:-



Download Zip Code


Example:-

CaffeineBeverage.java
package simple;

public abstract class CaffeineBeverage {

  final void prepareRecipe()
  {
    boilWater();
    brew();
    pourInCup();
    addCondiments();
  }
  abstract void brew();
  
  abstract void addCondiments();
  
  public void boilWater()
  {
    System.out.println("Boiling Water");
  }
  
  public void pourInCup()
  {
    System.out.println("Pouring in cup");
  }
}

CaffeineBeverageWithHook.java
package simple;

public abstract class CaffeineBeverageWithHook {

  final void prepareRecipe()
  {
    boilWater();
    brew();
    pourInCup();
    if(customerWantCondiments())
    {
      addCondiments();
    }
    
  }
  abstract void brew();
  
  abstract void addCondiments();
  
  public void boilWater()
  {
    System.out.println("Boiling Water");
  }
  
  public void pourInCup()
  {
    System.out.println("Pouring in cup");
  }
   boolean customerWantCondiments()
  {
    return true;
  }

}


Coffee.java
package simple;

public class Coffee extends CaffeineBeverage{
  void addCondiments() {    
    System.out.println("Adding Sugar and milk");
  }
  void brew() {
    System.out.println("Dripping Coffee through filter");    
  }
}

CoffeeWithHook.java
package simple;

public class CoffeeWithHook extends CaffeineBeverageWithHook{
  void addCondiments() {
    
    System.out.println("Adding Sugar and milk");
  }
  void brew() {
    System.out.println("Dripping Coffee through filter");
  }
   boolean customerWantCondiments()
    {
     
      return false;
    }
}

Tea.java
package simple;

public class Tea extends CaffeineBeverage{
  void addCondiments() {
    System.out.println("Adding lemon");
  }
  void brew() {
    System.out.println("Steeping the Tea");
  }
}

Test.java
package simple;

public class Test {

  public static void main(String[] args) {
    CaffeineBeverage cof=new Coffee();
    cof.prepareRecipe();
    Tea t=new Tea();
    t.prepareRecipe();
    CoffeeWithHook chook=new CoffeeWithHook();
    chook.prepareRecipe();
    
  }
}

Output:-



Download Zip code

Example:-

CheckBackground.java
package LoanApplication;

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()
    }
}


LoanApp.java
package LoanApplication;
class LoanApp extends CheckBackground {
    private String name;
   
    public LoanApp(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void checkBank() {
        //ck acct, balance
        System.out.println("check bank...");
    }

    public void checkCredit() {
        //ck score from 3 companies
        System.out.println("check credit...");
    }

    public void checkLoan() {
        //ck other loan info
        System.out.println("check other loan...");
    }

    public void checkStock() {
        //ck how many stock values
        System.out.println("check stock values...");
    }

    public void checkIncome() {
        //ck how much a family make
        System.out.println("check family income...");
    }
   
    //other methods
}


TestTemplate.java
package LoanApplication;

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();
    }
}

Output:-



Download Zip code

Example:

Deliverable.java
package pkg;

class Deliverable extends ProjectItem{
    private double materialsCost;
    private double productionTime;
    
    public Deliverable(){ }
    public Deliverable(String newName, String newDescription,
        double newMaterialsCost, double newProductionTime,
        double newRate){
        super(newName, newDescription, newRate);
        materialsCost = newMaterialsCost;
        productionTime = newProductionTime;
    }
    
    public void setMaterialsCost(double newCost)
materialsCost = newCost; }
    public void setProductionTime(double newTime)
productionTime = newTime; }
    
    public double getMaterialsCost(){ return materialsCost; }
    public double getTimeRequired(){ return productionTime; }
}


ProjectItem.java
package pkg;

import java.io.Serializable;

abstract class ProjectItem implements Serializable{
    private String name;
    private String description;
    private double rate;
    
    public ProjectItem(){}
    public ProjectItem(String newName,
 String newDescription, 
double newRate){
        name = newName;
        description = newDescription;
        rate = newRate;
    }
    
    public void setName(String newName){ name =
newName; 
}
    public void setDescription(String newDescription)
description = newDescription; }
    public void setRate(double newRate){ rate = newRate; }
    
    public String getName(){ return name; }
    public String getDescription(){ return description; }
    public final double getCostEstimate(){
        return getTimeRequired() * getRate()
 
+ getMaterialsCost();
    }
    public double getRate(){ return rate; }
    
    public String toString(){ return getName()}
    
    public abstract double getTimeRequired();
    public abstract double getMaterialsCost();
}

Task.java
package pkg;

import java.util.*;

class Task extends ProjectItem{
    private ArrayList projectItems = new ArrayList();
    private double taskTimeRequired;
    
    public Task(){ }
    public Task(String newName, String newDescription,
        double newTaskTimeRequired, double newRate){
        super(newName, newDescription, newRate);
        taskTimeRequired = newTaskTimeRequired;
    }
    
    public void setTaskTimeRequired(double newTaskTimeRequired)
taskTimeRequired = newTaskTimeRequired; }
    public void addProjectItem(ProjectItem element){
        if (!projectItems.contains(element)){
            projectItems.add(element);
        }
    }
    public void removeProjectItem(ProjectItem element){
        projectItems.remove(element);
    }
    
    public double getTaskTimeRequired(){ return
 
taskTimeRequired; }
    public Iterator getProjectItemIterator(){ return
 
projectItems.iterator()}
    public double getMaterialsCost(){
        double totalCost = 0;
        Iterator items = getProjectItemIterator();
        while (items.hasNext()){
            totalCost += ((ProjectItem)items.next()).
getMaterialsCost
();
        }
        return totalCost;
    }
    public double getTimeRequired(){
        double totalTime = taskTimeRequired;
        Iterator items = getProjectItemIterator();
        while (items.hasNext()){
            totalTime += ((ProjectItem)items.next())
.getTimeRequired
();
        }
        return totalTime;
    }
}

Test.java
package pkg;

public class Test {
    public static void main(String [] arguments){
        System.out.println("Example for the Template Method
 pattern"
);
        System.out.println("This code demonstrates how the
template method can"
);
        System.out.println(" be used to define a variable
implementation for a"
);
        System.out.println(" common operation. In this case
, the ProjectItem"
);
        System.out.println(" abstract class defines the method
 getCostEstimate,"
);
        System.out.println(" which is a combination of the cost
 for time and"
);
        System.out.println(" materials. The two concrete subclasses
used here,"
);
        System.out.println(" Task and Deliverable, have
different methods of"
);
        System.out.println(" providing a cost estimate.");
        System.out.println();
        
        System.out.println("Creating a demo Task and Deliverable");
        System.out.println();
        Task primaryTask = new Task("Put a JVM on the moon",
"Lunar mission as part of the JavaSpace program ;)"240.0100.0);
        primaryTask.addProjectItem(new Task("Establish ground
control"
""1000.010.0));
        primaryTask.addProjectItem(new Task("Train the Javanaughts",
 
""80.030.0));
        Deliverable deliverableOne = new Deliverable("Lunar landing
 module"
"Ask the local garage if they can make a few minor
modifications to one of their cars"
280040.035.0);
        
        System.out.println("Calculating the cost estimates using
 the Template Method, getCostEstimate."
);
        System.out.println();
        System.out.println("Total cost estimate for: "
+ primaryTask);
        System.out.println("\t" + primaryTask.getCostEstimate());
        System.out.println();
        
        System.out.println("Total cost estimate for: "
+ deliverableOne
);
        System.out.println("\t" + deliverableOne.getCostEstimate());
    }
}

Output:-


Download Zip Code