• B1:模板方法模式 TemplateMethod


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

    应用场景:

    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

  • 相关阅读:
    poj_1836 动态规划
    动态规划——最长上升子序列
    poj_3260 动态规划
    poj_3628 动态规划
    动态规划——背包问题
    poj_2559 单调栈
    poj_3415 后缀数组+单调栈
    poj_2823 线段树
    poj_2823 单调队列
    poj_3250 单调栈
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7788673.html
Copyright © 2020-2023  润新知