bbx*_*bby 5 php iterator design-patterns
我试图了解SPL迭代器,我想出了两种方法来处理它.我看到第一个版本不那么复杂,但第二个版本有它的构图感觉(我认为).
我没看到的是哪一个优于另一个?或者我只是让这复杂化?
这是我的想法:
该对象实现了一个迭代器:
class BoxOfChocolates implements Iterator {
private $id
private $name; // e.g. Valentine's Heart Box
private $maker; // e.g. Hersheys
private $items; // array
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}
Run Code Online (Sandbox Code Playgroud)
该对象包含一个可迭代的对象:
class BoxOfChocolates {
private $id;
private $name;
private $maker;
private $items; // chocolates object
public function getChocolates() {
$this->items = new Chocolates();
$this->items->getChocolates();
}
}
class Chocolates implements Iterator {
private $items;
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}
Run Code Online (Sandbox Code Playgroud)
小智 2
这取决于实际情况。这盒巧克力是否包含多个系列?如果是这样,您需要让集合成为成员。
这样想吧。一盒巧克力是一个集合(即 PersonList)还是拥有一个集合的东西(即一辆车可能拥有它最后一个拥有者的集合)。
我认为这属于第一组
:)