Friday, September 15, 2006

Template Pattern

A Template Pattern defines the skeleton of an algorithm. The algorithm itself is made abstract, and the subclasses of the method override the abstract methods to provide concrete behaviour.

This is particularly useful for separating the variant and the invariant behaviour, minimizing the amount of code to be written. The invariant behaviour is placed in the abstract class (template) and then any subclasses that inherit it can override the abstract methods and implement the specifics needed in that context.

First class is created that provides the basic steps of an algorithm. These steps are implemented using abstract methods. Later on, subclasses change the abstract methods to implement real actions. Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses.

The template method is used to:


  • let subclasses implement behaviour that can vary

  • avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses

  • to control at what point(s) subclassing is allowed.




public abstract class Benchmark{
/**
* Not Implement
*/
public abstract void benchmark();

/**
* repeat benchmark
*/
public final long repeat (int count) {
if (count < = 0)
return 0;
else {
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++)
benchmark();
long stopTime = System.currentTimeMillis();
return stopTime - startTime;
}
}
}

public class MethodBenchmark extends Benchmark
{
/**
* Implementation benchmark
*/
public void benchmark() {
for (int i = 0; i < Integer.MAX_VALUE; i++){
System.out.println("i="+i);
}
}
}

Once the benchmark change implementation, we just need to create another class with extend the abstract class and no need change others method.

No comments: