首页 > 其他 > 详细

B1:模板方法模式 TemplateMethod

时间:2017-11-05 21:05:50      阅读:232      评论:0      收藏:0      [点我收藏+]

定义一个操作中的算法骨架,而将一些步骤延迟到子类中.模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤

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

 

B1:模板方法模式 TemplateMethod

原文:http://www.cnblogs.com/itfenqing/p/7788673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!