template

=Template Method Pattern:=

The description of the Template Method Pattern is: The Template Method pattern is one of the simplest and most frequently used design patterns in object-oriented applications.

The Template Method pattern can be used in situations when there is an algorithm, some steps of which could be implemented in multiple different ways. In such scenarios, the Template Method pattern suggests keeping the outline of the algorithm in a separate method referred to as a template method inside a class, which may be referred to as a template class, leaving out the specific implementations of the variant portions (steps that can be implemented in multiple different ways) of the algorithm to different subclasses of this class.

The Template class does not necessarily have to leave the implementation to subclasses in its entirety. Instead, as part of providing the outline of the algorithm, the Template class can also provide some amount of implementation that can be considered as invariant across different implementations. It can even provide default implementation for the variant parts, if appropriate. Only specific details will be implemented inside different subclasses. This type of implementation eliminates the need for duplicate code, which means a minimum amount of code to be written.

The Template pattern is the definition of the relationship abstract classes have to their inherited members. This pattern defines the skeleton or template for a group of classes as a parent class, and allows inherited members to modify this template without changing the underlying template class.

The Template pattern has two components: the Template class and the Concrete class. The template is the base or abstract class that acts as the skeleton for all the shared functionality that gets inherited to the class instances, or concrete classes. Each concrete class can override the methods and functions of the template class or use these inherited methods without overriding them.

This pattern is the basic model for all inheritance of classes. Although the GoF doesn't say this directly, there are a couple of good rules to follow with this pattern. One is to limit the layers of inheritance to no deeper than two layers. This is to prevent over complication of your code by using too many inherited classes. If you find you need a variety of functionality for inherited members, and some inherited classes share this functionality and some do not need to, you might try a plug-and-play pattern like the Visitor pattern. The Visitor pattern gives a little more flexibility to add new functionality without using multiple layers of direct inheritance and without rewriting this functionality in the new members. This allows the sharing of functionality across classes, without the need for deep and complicated inherited members.



Abstract Class
This design is more suitable when the Template class provides only the outline of the algorithm without any default implementation for its variant parts. Assuming that different steps of the algorithm can be made into individual methods: In this design, the Abstract class declares methods and each of the subclasses implement these methods in a manner that is specific to it without altering the outline of the algorithm.
 * The Template method can be a concrete, non abstract method with calls to other methods that represent different steps of the algorithm.
 * The Template class can implement invariant parts of the algorithm as a set of non abstract methods.
 * The set of variant steps can be designed as abstract methods. Specific implementations can be provided for these abstract methods inside a set of concrete subclasses of the abstract Template class.

Concrete Class
This design is more suitable when the Template class provides, besides the outline of the algorithm, the default implementation for its variant parts. Assuming that different steps of the algorithm can be made into individual methods: From both the design strategies, it can be seen that the Template pattern implementation relies heavily on inheritance and function overriding. Hence, whenever inheritance is used for implementing the specifics, it can be said that Template Method pattern is used in its simplest form.
 * The Template method can be a concrete, non abstract method with calls to other methods that represent different steps of the algorithm.
 * The Template class can implement invariant parts of the algorithm as a set of non abstract methods.
 * The set of variant steps can be designed as non abstract methods with the default implementation. Subclasses of the Template class can override these methods to provide specific implementations without altering the outline of the algorithm.

Implementation
Abstract Classes defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. Abstract Classes implements a template method which defines the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in abstract classes or those of other objects. Concrete Classes implements the primitive operations to carry out subclass-specific steps of the algorithm. When a concrete class is called the template method code will be executed from the base class while for each method used inside the template method will be called the implementation from the derived class.

Applicability & Examples
The Template Method pattern should be used:
 * To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
 * When refactoring is performed and common behavior is identified among classes. An abstract base class containing all the common code (in the template method) should be created to avoid code duplication.

Comparison to Similar Patterns
The Template pattern is related to almost all the other patterns in some fashion. Since it defines the relationship between a parent class and its inherited members, the Template pattern can be seen in usage with most of the other patterns in some way. The Template pattern gives us the very basic and useful relationship definition between a parent class and all its subclasses. It allows us to establish the inherited relationship for sharing and defining class structures, for use in polymorphic transitions in class types at run time or in code flow. Related Patterns to the Template Pattern are: Abstract Factory, Adapter, Bridge, Builder, Chain of Responsibility, Command, Factory, Flyweight, Mediator, Observer, Prototype, Strategy, and Visitor The strategy pattern is with Template Method pattern. The difference consists in the fact that Strategy uses delegation while the Template Methods uses the inheritance.

Concrete base class
It is not necessary to have the superclass as an abstract class. It can be a concrete class containing a method (template method) and some default functionality. In this case the primitive methods cannot be abstract and this is a flaw because it is not so clear which methods have to be overridden and which not. A concrete base class should be used only when customizations hooks are implemented.

Template method cannot be overridden
The template method implemented by the base class should not be overridden. The specific programming language modifiers should be used to ensure this.

Customization Hooks
A particular case of the template method pattern is represented by the hooks. The hooks are generally empty methods that are called in superclass (and does nothing because are empty), but can be implemented in subclasses. Customization Hooks can be considered a particular case of the template method as well as a totally different mechanism.

Minimizing primitive methods number
It's important when designing template methods to minimize the number of primitive methods that a subclass must override in order to provide a clear an easy way to implement concrete templates.

Naming Conventions
In order to identify the primitive methods is it better to use a specific naming convention. For example the prefix “do” can be used for primitive methods. In a similar way the customizations hooks can have prefixes like “pre” and “post”.

Special Issues
Template method is using as an inverted controls structure, sometimes referred as “the Hollywood principle”: from the superclass point of view: “Don't call us, we'll call you”. This refers to the fact that instead of calling the methods from base class in the subclasses, the methods from subclass are called in the template method from superclass. Due to the above fact a special care should be paid to the access modifiers: the template method should be implemented only in the base class, and the primitive method should be implemented in the subclasses. A particular case of the template method is represented by the customization hooks.

Code Example 1:
The following code will create a template class called Automobile. From that we will use this template that will do basic things that other automobiles do or have, like start, and accelerate. Then we will use this template to create other classes such as Truck and Sedan, which are two different types of Automobiles.

//**Filename: TestTemplateAutomobile.java**// code format="java" public class TestTemplateAutomobile { public static void main(String args[]) { Sedan Camry = new Sedan("Sedan"); Truck Tundra = new Truck("Truck"); Camry.go; Tundra.go; } }

class Truck extends Automobile { private String name;

public Truck(String n) { name = n; }

public void doTuneUp { System.out.println("do tune up on Truck...."); }

public void rotateTires { System.out.println("Rotate Truck's tires...."); }

public void accelerate { System.out.println("Make the truck accelerate..."); }

public String getName { return name; } }

class Sedan extends Automobile { private String name;

public Sedan(String n) { name = n; }

public void doTuneUp { System.out.println("Getting a Tune Up Done on the Sedan..."); }

public void rotateTires { System.out.println("Rotating the Sedan's tires...."); }

public void accelerate { System.out.println("Accelerating the Sedan...."); }

public String getName { return name; } }

abstract class Automobile { public final void go { start; doTuneUp; rotateTires; accelerate; stop; }

public void start { System.out.println("Starting...."); }

public void doTuneUp { System.out.println("do general Tune Up ..."); }

public void rotateTires { System.out.println("Rotating Tires...."); }

public void accelerate { System.out.println("Accelerating...."); }

public void stop { System.out.println("Stopping...."); } }

code

**Output 1:**

Code Example 2:
The following code will create an abstract template class called TemplateTest, that will print out the output of both implementations of the code.


 * //Filename: TemplateMethodSample.java//**

code format="java" abstract class TemplateTest { public TemplateTest { templateMethod; }

abstract void implementation1; abstract void imlementation2;

// here we will print 8 times both implementations of the main class TemplateTest final void templateMethod { for (int i = 0; i < 8; i++) { implementation1; imlementation2; } } }

class MyApp extends TemplateTest { void implementation1 { System.out.print("First "); }

void imlementation2 { System.out.println(" Second!"); } }

public class TemplateMethodSample { public static void main(String args[]) { MyApp app = new MyApp; } }

code

**Output 2:**

Template Pattern wrap up
The Template pattern gives us the very basic and useful relationship definition between a parent class and all its subclasses. It allows us to establish the inherited relationship for sharing and defining class structures, for use in polymorphic transitions in class types at run time or in code flow.

Introduction **TEMPLATE**  Iterator


 * Chapters **