In this article, I would like to present you a design pattern that is not so common, but for sure, I wish, that in the past I would have used it. It would certainly make my life much easier. So, what is this Template method pattern all about?

The Template Method Pattern defines the skeleton of a an algorithm in one method. Some steps are deferred to subclasses, which are allowed to alter certain algorithm steps without changing the skeleton of an algorithm.

Say what?

Well, to simplify the definition, let’s look at an example. Imagine you have several product types. Your assigned task was to build a product catalogue on the web. All product types will use tables for representation, however not all products can be displayed the same. This is a perfect task for Template method pattern.

But why?

Think about it. Your catalogue needs to be displayed differently for each product, meaning you need to get different sets of product for each display. I agree, you could have written multiple agents, or just use multiple methods in an agent, but think about maintainability. And on top of it all, to display each product type, your algorithm is the same. First you need to do some initialization, then you need to select desired products. Next step is to process document set to create a display. In the end, all you need to do is print the results and terminate (or perform a clean up). Steps select and process are product type dependant. All other steps of the algorithm are common.

Example

For example let’s pretend that we have two types of products: regular classroom courses and e-courses. Regular classroom courses (or just courses) are scheduled courses, while e-courses are actually a 1 month subscription to some content (like video, PDF, etc.).

First, we need to create some storage classes: CProduct and CPrice, that will store information about products. This is more efficient than just have a collection of NotesDocuments.

Class CPrice contains a description of price (subscription or schedule date) and the price itself. Class CProduct defines a product. Each product can have multiple prices.

Now, to our abstract class that will define the algorithm and required methods.

As you can see, methods Initialize, Print and Terminate are already implemented.
Next, we need to create classes for each product type. These classes will inherit from the abstract class.

As you can no doubt see, I have simplified the Select method (this is due to me being to lazy to actually create a form, a view and some 6 documents). Also, method Process creates different HTML for each product type.

Interesting thing, this is about it.
All you have to do is some code that will use this. Here is my test agent, that should be run via browser.