Thursday, October 28, 2010

How To Wear A Kilt Belt

Design Patterns: Template Method

Estre defines the operation pattern a general algorithm in an operation of a class by delegating to other classes through inheritance or dependency between classes, the specific implementation of each of its steps. Let these classes redefine certain steps of the algorithm without changing the general behavior, adapting each to a specific need.

A classical implementation of this pattern is the one in the book "Design Patterns" GOF, which presents an abstract class that defines the general behavior of an operation on a particular method in turn calls other abstract methods that define specific behaviors. Different Subclasses can inherit from this class and specify different behavior for abstract methods, allowing multiple implementations that can be adjusted to every need.

The following UML diagram shows an example based on this way of implementing the Template Method pattern :

In it, a class Game method defined in its play () general behavior of any game The game starts and each player is making his move until it meets a condition that ends the game and displays the result. These operations are indicated by abstract methods that must be implemented by each appropriately specific game, such as the Parchis or Chess.

However, when the inheritance is stronger coupling between classes, looking for more flexible proposed an alternative implementation based on the dependency between classes instead of inheritance.

The following diagram shows an example implementation of the Template Method pattern using the dependency between classes:

It shows a template class with a method JuegoTemplate play () that defines the general behavior of any game. As before, the game starts and each player is making his move until it meets a condition that ends the game and displays the result. These operations are carried out by an instance of a class that implements the game, which specifies the métodosque interface must be implemented for each specific game. Parchis classes and Chess Game implement the interface and define the specific behavior of these games.

This way to implement the Template Method pattern is used Spring to provide, for example, support access to JDBC Hibernate or through their staff HibernateTemplate JDBCTemplate or that use an instance of a class that implements the DataSource interface that encapsulates the behavior and specific access to a data source.

References:
Design Patterns (Erich Gamma, Richard Helm, Ralph Johnson, Vlissides Hohn)
Template Method Pattern in Wikipedia
Implementation of Template pattern using composition and injection
The Template Design Pattern Template Method Pattern

Other design patterns