定义一个操作中的算法骨架,而将一些步骤延迟到子类中.模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤
应用场景:
A.操作步骤稳定,而具体细节延迟到子类.
UML:

示例代码:
所有的商品类在用户购买前,都需要给用户显示出最终支付的费用.但有些商品需要纳税,有些商品可能有打折.
abstract class Product
{
protected $payPrice = 0;
public final function setAdjustment()
{
$this->payPrice += $this->discount();
$this->payPrice += $this->tax();
}
public function getPayPrice()
{
return $this->payPrice;
}
protected function discount()
{
return 0;
}
abstract protected function tax();
}
class CD extends Product
{
public function __construct($price)
{
$this->payPrice = $price;
}
protected function tax()
{
return 0;
}
}
class IPhone extends Product
{
public function __construct($price)
{
$this->payPrice = $price;
}
protected function tax()
{
return $this->payPrice * 0.2;
}
protected function discount()
{
return -10;
}
}
$cd = new CD(15);
$cd->setAdjustment();
echo $cd->getPayPrice();
$iphone = new IPhone(6000);
$iphone->setAdjustment();
echo $iphone->getPayPrice();
ps:一般为防止模板下属类修改模板,模板方法都会加上final