<?php
//模板设计模式创建了一个实施一组方法和功能的抽象对象,子类通常将这个对象作为模板用于自己的设计。
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 * 0.05, 2);
}
}
class BandEndorsedCaseOfCereal 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 * 0.2, 2);
}
}
$externalTitle = 'fenghuangchuanqi';
$externalBand = 'zuixuanminzufeng';
$externalCDPrice = 100;
$externalCerealPrice = 200;
$cd = new CD($externalBand, $externalTitle, $externalCDPrice);
$cd->setPriceAdjustments();
echo 'The total cost for CD item is:'.$cd->price.PHP_EOL;
$cereal = new BandEndorsedCaseOfCereal($externalBand, $externalCerealPrice);
$cereal->setPriceAdjustments();
echo 'The total cost for Cereal item is:'.$cereal->price.PHP_EOL;
//创建定义了设计常规步骤,但实际逻辑留给子类进行详细说明的对象时,最佳的做法是使用模板设计模式。