Design Patterns Reference: Template

“The Template Design Pattern creates an abstract object that enforces a set of methods and functionality that will be used in common by child classes as a template for their own design.”

 

abstract class SaleItemTemplate
{
public $price = 0;

 

public final function setPriceAdjustments()
{
$this->price += $this->taxAddition();
$this->price += $this->oversizedAddition();
}

 

protected function oversizedAddition()
{
return 0;
}

 

abstract protected function taxAddition();
}

 

class CD extends SaleItemTemplate
{
public $band;
public $title;

 

public function __construct($band, $title, $price)
{
$this->band = $band;
$this->title = $title;
$this->price = $price;
}

 

protected function taxAddition()
{
return round($this->price * .05, 2);
}
}

 

class BandEndorsedCaseOfCerial extends SaleItemTemplate
{
public $band;

 

public function __construct($band, $price)
{
$this->band = $band;
$this->price = $price;
}

 

protected function taxAddition()
{
return 0;
}

 

protected function oversizedAddition()
{
return round($this->price * .20, 2);
}
}

 

// use
$externalTitle = “Waste of a Rib”;
$externalBand = “Never Again”;
$externalCDPrice = 12.99;
$externalCerealPrice = 90;
$cd = new CD($externalBand, $exteralTitle, $externalCDPrice);
$cd->setPriceAdjustments();

 

print ‘The total cost for CD item is: $’ . $cd->price;

 

$cereal = new BandEndorsedCaseOfCerial($externalBand, $externalCerealPrice);
$cereal->setPriceAdjustments();

 

print ‘The total cost for the Cereal case is: $’ . $cereal->price;

 

“When creating an object where the general steps of a design are defined but the actual logic is left to be detailed by a child class, using the Template Design Pattern is best practice.”

 

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

 

 

Leave a Reply

You must be logged in to post a comment.