The use of the Template Method template has two main characteristics:
- There is a base class (in Java, one with
protected constructors only and optionally declared as abstract ) that will be subclassed in client code. - In the base class, two groups of methods are defined: a) one or more template methods (usually only one) and one or more primitive methods of work (usually more than one). Each template method is a high-level operation implemented in the base class in terms of primitive operations that must be implemented / redefined in each particular subclass. Typically, a template method is public and non-redefined (
final , in Java); his API documentation should determine exactly what primitive working methods he calls, and when (that is, he should describe the "algorithm"). The primitive operation method, which is a step in the algorithm, must be non-public, but redefined ( protected , in Java) and can be of two types: a) an abstract method, which must be implemented in a subclass; b) a method with a default / empty implementation that can be overridden in a subclass.
One good example in the Java 6 SDK is the execute() method of the javax.swing.SwingWorker class (this is the public final void method). In this case, the primitive working methods are doInBackground() , process(List) and done() . The first is abstract and therefore requires implementation in a subclass; it is called by the template method in the background thread. The other two have empty implementations and can be overridden in a subclass; they are called during and at the end of processing, respectively, in the EDT (Swing Event Dispatch Thread) to allow updates to the user interface.
In my own experience, I sometimes used this template. One such case was a Java base class that implements the java.util.Iterator interface, where next() was a template method, and there was only one primitive working method responsible for creating an instance of a specific domain entity class (this was intended for use in iterating over a list Permanent Domain Entity Objects Using JDBC). The best example in the same application was the base class in which the template method implemented a multi-stage algorithm designed to populate the "business object maintenance screen" (using Swing) from a specific list of persistent objects; primitive methods of operations were called: 1) clear the current state of the screen and 2) add an object in the form of a table inside the screen; optionally, other primitive operations were called from the template method, if the screen was editable.
In the end, I have to say that, although this is certainly a useful design template, the situation does not often arise when it is really applicable. Just having a base class with methods that are redefined in a subclass (a much more common situation, in my experience) is not enough in itself to qualify as a template application.
Rogerio
source share