php:template

# Differences

This shows you the differences between two versions of the page.

 php:template [2013/03/16 17:40] php:template [2013/03/16 17:40] (current) Line 1: Line 1: + ==== TEMPLATE METHOD PATTERN ==== + 14.04.2010 + + {{:​php:​templatepattern.png?​nolink&​| Template Pattern }} + <​newcolumn>​ + A template method defines the program skeleton of an algorithm. One or more of the algorithm steps are able to be overridden by subclasses to provide their own concrete implementation. This allows differing behaviors while ensuring that the overarching algorithm is still followed. + + Subclasses change the abstract methods to implement real actions. Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses. + ​ + + + ​_getFirstNumber();​ + \$b = \$this->​_getSecondNumber();​ + return \$this->​_operator(\$a,​ \$b); + } + } + + /** + * A ConcreteClass. + */ + class Sum extends BinaryOperation + { + private \$_a; + private \$_b; + + public function __construct(\$a = 0, \$b = 0) + { + \$this->​_a = \$a; + \$this->​_b = \$b; + } + + protected function _getFirstNumber() + { + return \$this->​_a;​ + } + + protected function _getSecondNumber() + { + return \$this->​_b;​ + } + + protected function _operator(\$a,​ \$b) + { + return \$a + \$b; + } + } + + /** + * A ConcreteClass. + */ + class NonNegativeSubtraction extends BinaryOperation + { + private \$_a; + private \$_b; + + public function __construct(\$a = 0, \$b = 0) + { + \$this->​_a = \$a; + \$this->​_b = \$b; + } + + protected function _getFirstNumber() + { + return \$this->​_a;​ + } + + protected function _getSecondNumber() + { + return min(\$this->​_a,​ \$this->​_b);​ + } + + protected function _operator(\$a,​ \$b) + { + return \$a - \$b; + } + + } + + // Client code + \$sum = new Sum(84, 56); + echo \$sum->​getOperationResult(),​ "​\n";​ + \$nonNegativeSubtraction = new NonNegativeSubtraction(9,​ 14); + echo \$nonNegativeSubtraction->​getOperationResult(),​ "​\n";​ + ​ + + + **Credits**:​ [[http://​giorgiosironi.blogspot.com/​2010/​04/​practical-php-patterns-template-method.html | Giorgio Sironi]]