Template Method

From CDOT Wiki
Revision as of 17:05, 19 March 2007 by Ayfung (talk | contribs) (Code Samples)
Jump to: navigation, search

Template Method

Template Method, a class behavioral pattern, provides the general steps of a method while deferring the implementation to its subclasses. Used to encapsulate algorithms, it can help reduce code duplication and maximizes the reuse of subclasses. Generally, an abstract base class is created, defining a template method of an algorithm. Later on, the subclasses can alter and implement the behavior.

UML Diagram

Code Samples

public abstract class TitleInfo {  
   private String titleName;
   
   //the "template method" - 
   //  calls the concrete class methods, is not overridden
   public final String ProcessTitleInfo() {
       StringBuffer titleInfo = new StringBuffer();

       titleInfo.append(this.getTitleBlurb());
       titleInfo.append(this.getDvdEncodingRegionInfo());
       
       return titleInfo.toString();
   }  
   
   //the following 2 methods are "concrete abstract class methods"
   public final void setTitleName(String titleNameIn) {
       this.titleName = titleNameIn;
   }
   public final String getTitleName() {
       return this.titleName;
   }
   
   //this is a "primitive operation", 
   //  and must be overridden in the concrete templates
   public abstract String getTitleBlurb();
   
   //this is a "hook operation", which may be overridden, 
   //hook operations usually do nothing if not overridden 
   public String getDvdEncodingRegionInfo() {
       return " ";
   }
}

References

Links

BTP600