Rusty Divine

Live, Love, Learn, Teach

Learning Design Patterns – Template Method Pattern

This week I'll be examining the Template Method Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?
The Template Method Pattern lays out the steps in a process (algorithm) and allows subclasses to handle one or more of the steps internally. The pattern has a method that just contains a list of method calls to complete the process (create something, package it, sort it, deliver) that can not be overriden or augmented. Some of the process methods may be handled by the pattern (create something and deliver), while it makes the subclasses handle the others (sort it, package it).

The pattern also can have "hooks" in it, which are methods that have no implementation, or a default implementation, that the subclasses can choose to override or not.

Where is it used?
The Template Method Pattern is one of the most frequently used patterns around. It especially comes in handy for developing frameworks.

But why?
The Template Method Pattern encapsulates algorithms, and is used wherever a process, or some steps in a process, are being duplicated by classes - the pattern allows the code to be refactored so that the duplication can be eliminated by pulling that code into the pattern.

OK, and how is it implemented?

//Java

abstract class ShipSoftware {

	//declare the template method final so that it cannot be overridden
	final void ship {
		createMedia();
		packageMedia();
		postalSortByZip();
		deliver();
	}

	//make the subclass decide whether to put the software
	//on a CD or DVD or other medium
	abstract void createMedia();

	void packageMedia() {
		system.out.println("Putting software in a box");
	}

	void postalSortByZip() {
		system.out.println("Sorting packages by zip code to decrease shipping rates");
	}

	void deliver() {
		system.out.println("Drop off packages at Post Office");
	}

}


public class ShipMyNewestProduct extends ShipSoftware {

	//implement the creation
	public void createMedia() {
		system.out.println("Burn software on CD");
	}
}
blog comments powered by Disqus