Template Method Pattern
October 9, 2012 Leave a comment
It defines steps of an algorithm and lets sub-classes decide which steps to override.
In core java, java.util.Comparable interface is based on this pattern. Here sorting algorithm is already defined in Arrays class and steps in sort algorithm (compareTo()) is left to the user defined class(Duck.java).
public class Duck implements Comparable { String name; int weight; public Duck(String name, int weight) { this.name = name; this.weight = weight; } public String toString() { return name + " weighs " + weight; } public int compareTo(Object object) { Duck otherDuck = (Duck)object; if (this.weight < otherDuck.weight) { return -1; } else if (this.weight == otherDuck.weight) { return 0; } else { // this.weight > otherDuck.weight return 1; } } } // client to sort instances of Duck class public class DuckSortTestDrive { public static void main(String[] args) { Duck[] ducks = { new Duck("Daffy", 8), new Duck("Dewey", 2), new Duck("Howard", 7), new Duck("Louie", 2), new Duck("Donald", 10), new Duck("Huey", 2)}; System.out.println("Before sorting:"); display(ducks); // sort Arrays.sort(ducks); System.out.println("\nAfter sorting:"); display(ducks); } public static void display(Duck[] ducks) { for (int i = 0; i < ducks.length; i++) { System.out.println(ducks<em>); } } }
Recent Comments