<?php abstract class Account { public $next; public $balance; public function setNext(Account $account) { $this->next = $account; } public function canPay($amount) { return $this->balance >= $amount; } public function pay($amount) { if ($this->canPay($amount)) { echo 'Paying ' . $amount . ' using ' . get_called_class() . PHP_EOL; } elseif ($this->next) { $this->next->pay($amount); } else { throw new Exception("Can not pay"); } } } class PayA extends Account { public function __construct($balance) { $this->balance = $balance; } } class PayB extends Account { public function __construct($balance) { $this->balance = $balance; } } class PayC extends Account { public function __construct($balance) { $this->balance = $balance; } } $payA = new PayA(100); $payB = new PayB(200); $payC = new PayC(300); $payA->setNext($payB); $payB->setNext($payC); $payA->pay(259);
一天一个设计模式(12)——责任链模式
本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7200576.html