0

我正在将我的程序 php 项目转换为 OOP。我坚持一个问题。检索表数据的最佳方法是什么?

使用构造函数传递 id

new Rate(new Currency($currencyId), $amount);

还是首先设置 id 并调用 getId() 方法?

$currency = (new Currency())->setId($currencyId);
new Rate($currency->getId(), $amount)
4

3 回答 3

2

Rate对象不应该关心是什么,而$currencyId它唯一应该知道的是有一种货币:

$rate = new Rate(new Currency($currencyId), $amount);

如果要防止实例化太多Currency对象,可以引入映射器:

$mapper = new CurrencyMapper();
$rate = new Rate($mapper->getCurrencyWithId($currencyId), $amount);

应该注意的是,根据Flyweight的规则,执行此操作时所有对象都必须是不可变的。

于 2013-07-05T07:55:35.023 回答
1

问一个关于 OOP 设计的问题,你会得到 100 个不同的答案。有许多不同的设计模式可以完成同样的事情。

很难说,因为我们没有看到您的完整设计,但是鉴于您的 2 个示例,我会选择第一个。

于 2013-07-05T05:56:40.483 回答
0

Just from the viewpoint of readability and the number of calls made I'd go with the first one. The second one makes two separate calls (one to the constructor and another one to set $currencyId).

于 2013-07-05T07:48:15.890 回答