Template Method Pattern

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

Diabolical or Smart

Nitwit, Blubber, Oddment, Tweak !!

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey