Difference between revisions of "Template Method"

From CDOT Wiki
Jump to: navigation, search
(Code Samples)
(Pseudo Code)
Line 9: Line 9:
  
 
<pre>
 
<pre>
abstract class AbstractRenderer
+
//coercion polymorphism
{
+
abstract class Add {
// Define the order in which the graphical routines should be executed
+
  public abstract double add(double d1, double d2);//template
void render()
 
{
 
// First draw the graphics
 
drawGraphics();
 
 
// Then draw the GUI on top of the graphics
 
drawGUI();
 
}
 
 
void drawGraphics();
 
void drawGUI();
 
 
}
 
}
+
class AddAnyTypeNumber extends Add{
class Renderer extends AbstractRenderer
+
    public double add(double d1, double d2) {
{
+
        return d1 + d2;
void drawGraphics()
+
    }
{
+
}
// Draw the graphics here
+
class Test {
}
+
  public static void main(String[] args) {
+
      double d1 = 10.5, d2 = 9.5;
void drawGUI()
+
      float f1 = 11.5f, f2 = 12.5f;
{
+
      long l1 = 1, l2 = 2;
// Draw the graphical user interface here
+
      int i1 = 3, i2 = 4;
}
+
      short s1 = 7, s2 = 8;
 +
      byte b1 = 5, b2 = 6;
 +
     
 +
      AddAnyTypeNumber addNumber = new AddAnyTypeNumber();
 +
     
 +
      System.out.println(addNumber.add(d1,d2));
 +
      System.out.println((float)addNumber.add(f1,f2));
 +
      System.out.println((long)addNumber.add(l1,l2));
 +
      System.out.println((int)addNumber.add(i1,i2));
 +
      System.out.println((short)addNumber.add(s1,s2));
 +
      System.out.println((byte)addNumber.add(b1,b2));
 +
  }
 
}
 
}
 
</pre>
 
</pre>

Revision as of 17:18, 19 March 2007

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

Pseudo Code

//coercion polymorphism
abstract class Add {
   public abstract double add(double d1, double d2);//template
}
class AddAnyTypeNumber extends Add{
    public double add(double d1, double d2) {
        return d1 + d2;
    }
}
class Test {
   public static void main(String[] args) {
       double d1 = 10.5, d2 = 9.5;
       float f1 = 11.5f, f2 = 12.5f;
       long l1 = 1, l2 = 2;
       int i1 = 3, i2 = 4;
       short s1 = 7, s2 = 8;
       byte b1 = 5, b2 = 6;
       
       AddAnyTypeNumber addNumber = new AddAnyTypeNumber();
       
       System.out.println(addNumber.add(d1,d2));
       System.out.println((float)addNumber.add(f1,f2));
       System.out.println((long)addNumber.add(l1,l2));
       System.out.println((int)addNumber.add(i1,i2));
       System.out.println((short)addNumber.add(s1,s2));
       System.out.println((byte)addNumber.add(b1,b2));
   }
}

References

Links

BTP600