抽象类的应用就是典型的模版模式
抽象类的应用就是典型的模版模式,先声明一个不能被实例化的模版,在子类中去依照模版实现具体的应用。
我们写这样一个应用:
银行计算利息,都是利率乘以本金和存款时间,但各种存款方式计算利率的方式不同,所以,在账户这个类的相关方法里,只搭出算法的骨架,但不具体实现。具体实现由各个子类来完成。
02 |
abstract class LoanAccount
|
05 |
protected $interest,$fund;
|
06 |
public function calculateInterest()
|
09 |
$this->interest = getInterestRate();
|
11 |
$this->interest = $this->getFund() * $this->getInterestRate();
|
12 |
return $this->interest;
|
14 |
private function getFund()
|
22 |
protected abstract function getInterestRate();
|
以后,所有和计算利息的类都继承自这个类,而且必须实现其中的 getInterestRate() 方法,这种用法就是模版模式。
相关文章: