我首先将域模型(支票、银行等)与视图(支票的打印方式)分开。这是MVC模式背后的基本思想,其目标之一是允许以不同的方式显示相同的域模型(这似乎是你的情况)。因此,我将首先创建域类,例如:
class Cheque
{
protected $bank;
protected $money;
...
}
class Bank {...}
请注意,这些类是 MVC 三元组的“M”,并实现域模型的逻辑,而不是与渲染过程相关的行为。下一步是实现用于呈现支票的 View 类。采用哪种方法在很大程度上取决于您的渲染有多复杂,但我会从一个ChequeView
渲染公共部分的类开始,并将可以更改的特定部分委托给其他子视图(在本例中为日期):
abstract class ChequeView
{
protected $cheque;
protected $dateView;
public function __construct($cheque)
{
$this->cheque = $cheque;
$this->dateView = //Whatever process you use to decide if the payment date is shown or not
}
public function render()
{
$this->coreRender();
$this->dateView->render();
}
abstract protected function coreRender();
}
class BankACheckView extends ChequeView
{
protected function coreRender() {...}
}
class BankBCheckView extends ChequeView
{
protected function coreRender() {...}
}
abstract class DateView
{
abstract function render()
}
class ShowDateView extends DateView
{
function render() {...}
}
class NullDateView extends DateView
{
function render() {...}
}
而且,如果有代码可以跨子类重用,您当然可以将它们考虑在内ChequeView
并coreRender()
调用它们。
In case your rendering turns to be too complex, this design may not scale. In that case I would go for splitting your view in meaningful subparts (e.g. HeaderView
, AmountView
, etc) so that rendering a cheque becomes basically rendering its different sub-parts. In this case the ChequeView
may end basically working as a Composite. Finally, if you reach this case and setting up the ChequeView
turns out to be a complex task you may want to use a Builder.
Edit based on the OP comments
The Builder is mostly used when the instantiation of the final object is a complex process (e.g. there are many things to sync between the sub-parts in order to get a consistent whole). There is generally one builder class and different clients, that send messages (potentially in different orders and with different arguments) to create a variety of final objects. So, while not prohibited, it is not usual to have one builder per type of object that you want to build.
If you are looking for a class that represents the creation of a particular instance you may want to check the Factory family of patterns (maybe the Abstract Factory resembles closely to what you had in mind).
HTH