Difference between revisions of "Template Method"
(→Pseudo Code) |
(→Pseudo Code) |
||
Line 6: | Line 6: | ||
== UML Diagram == | == UML Diagram == | ||
− | == | + | == Code Examples == |
=== Java === | === Java === | ||
<pre> | <pre> |
Revision as of 16:32, 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
Code Examples
Java
//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)); } }
Source from Javacamp, http://www.javacamp.org/designPattern/template.html/
PHP 5.0
abstract class AbstractClass { public final function templateMethod() { print "AbstractClass::templateMethod() called.\n"; $this->mandatoryOperation(); $this->optionalOperation(); } protected abstract function mandatoryOperation(); protected function optionalOperation() { } } class ConcreteClass extends AbstractClass { protected function mandatoryOperation() { print "ConcreteClass::mandatoryOperation() called.\n"; } protected function optionalOperation() { print "ConcreteClass::optionalOperation() called.\n"; } }
Source from Zend Technologies, http://www.zend.com/zend/php5/php5-OOP.php?article=php5-OOP&kind=ph&id=3204&open=1&anc=0&view=1