PHP面向对象之旅:模板模式(转)

抽象类的应用就是典型的模版模式

抽象类的应用就是典型的模版模式,先声明一个不能被实例化的模版,在子类中去依照模版实现具体的应用。

我们写这样一个应用:

银行计算利息,都是利率乘以本金和存款时间,但各种存款方式计算利率的方式不同,所以,在账户这个类的相关方法里,只搭出算法的骨架,但不具体实现。具体实现由各个子类来完成。

01 <?
02 abstract class LoanAccount
03 {
04     //利息,本金
05     protected $interest,$fund;
06     public function calculateInterest()
07     {
08         // 取得利率
09         $this->interest = getInterestRate();
10         //用于计算利息的算法:本金*利率,但是利率的算法实现并没有在这个类中实现
11         $this->interest = $this->getFund() * $this->getInterestRate();
12         return $this->interest;
13     }
14     private  function getFund()
15     {
16         return $this->fund;
17     }
18     //… …
19     /*不同的存款类型有不同的利率, 因此,不在这个父类中实现利率的计算方法,
20     *  而将它推迟到子类中实现
21     */
22     protected abstract function  getInterestRate();
23 }
24 ?>

以后,所有和计算利息的类都继承自这个类,而且必须实现其中的 getInterestRate() 方法,这种用法就是模版模式。

原文地址:https://www.cnblogs.com/xingmeng/p/3237644.html