Noah Subrin's DEV Blog
Technology for Business minds

Template Method Design Pattern

Print the article

This entry was posted on 11/4/2006 9:35 AM and is filed under Design Patterns.

On Wednesday, November 1, 2006 I taught my SRA-U Design Patterns class. We discussed the Template Method Pattern. The Template Method Pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

The Template method is a good choice for a design pattern under the following conditions:
1) When we wish to implement the parts of an algorithm that do not change and leave it up to subclasses to implement the behavior that does change.

2) When we want to refactor to avoid code duplication.

3) To control subclasses extensions. We can define a template method that calls “hooks” operations at specific points, thereby permitting extensions only at these points.

In the real world, the Template Method is used in the .Net Framework when we create user controls and server controls and we wish to hook into certain default events, for example the Init Event or the OnPaint Event. Another classic use of the Template Method is for sorting. I demonstrated some code that will allow the user to sort an ArrayList of class objects on the fly by an arbitrary property selected by the user at run-time.

I also briefly discussed the Template Method in the Java platform. It can be used to hook into events for Applets and JFrame (forms).

My slide deck for the Template Method can be dowloaded here: Template method Slides




Next weeks class will cover the Iterator and Composite Patterns.

 

What did you think of this article?




Trackbacks
Trackback specific URL for this entry
  • No trackbacks exist for this entry.
Comments
    • No comments exist for this entry.
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.