Skip to content

The Template Method Pattern

Template pattern comes under behavior pattern group, as it’s used to manage algorithms, relationships and responsibilities between objects. This is an easy Pattern to understand, Let’s dig in,

In Template pattern, an abstract base class exposes defined templates to execute its methods. Its ConcreteClasses can override the method implementation as per need but without changing the algorithm’s structure and invocation.

So we can say, In Base class we declares algorithm ‘placeholders’, and ConcreteClasses implement the placeholders.

This particular design pattern is very useful , to avoid code duplication.By suing this pattern you let subclasses implement the behavior through overriding parent class algorithm.

there are four different types of methods used in the parent class:

Abstract methods
Method that are declared without any body within an abstract class is known as abstract method. The method body will be defined by its subclass. Any class that extends an abstract class must implement all the abstract methods declared by the super class.

Concrete methods
This methods are usually utility methods.These are standard complete methods that are useful to the subclasses.

Hook methods
Methods containing a default implementation that may be overridden in some classes. Hook methods are intended to be overridden.

Template methods
A method that calls any of the methods listed above in order to describe the algorithm without needing to implement the details.

Template Method Pattern Example

_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";


0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments