我正在努力将访问者模式应用于一些具有标量成员并同时聚合成员(集合)的对象。
这些是我拥有的对象:
Artist
- id
- name
- .. more scalar values ..
- worksOfArt <-- this is a collection as WorkOfArt instances
WorkOfArt
- id
- name
- .. more scalar values ..
- artists <-- this is a collection of Artist instances
如您所见,该结构也将是递归的,但这是我以后关心的问题。;-)
我的问题是:实现访问者模式的最佳方式是什么,它允许我访问对象以及它们的可访问子项(集合)。
我想创建一个这样的界面:
VisitableAggregateInterface
{
public function getVisitableChildren(); // this would return only visitable children
}
然后让 Artist 和 WorkOfArt 都像这样扩展一个抽象类:
VisitableAggregateAbstract implements VisitableAggregateInterface
{
public function accept( Visitor $visitor )
{
$visitor->visit( $this );
foreach( $this->getVisitableChildren() as $visitableChild )
{
$visitableChild->accept( $visitor );
}
}
/*
VisitableAggregateInterface::getVisitableChildren()
will be implemented by Artist and WorkOfArt and will only
return visitable children (like collections), and not scalar values.
*/
}
最终目标是最终得到一个具体的访问者,它将写出一个类似于以下内容的 XML 文件:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<artgallery>
<artists>
<artist>
<id>1</id>
<name></name>
<worksOfArt>
<workOfArt refid="11"/>
<workOfArt refid="12"/>
</worksOfArt>
<artist>
<artists>
<worksOfArt>
<workOfArt>
<id>11</id>
<artists>
<artist refid="1"/>
</artists>
<name></name>
<info><![CDATA[some info]]></info>
</workOfArt>
<workOfArt>
<id>12</id>
<artists>
<artist refid="1"/>
</artists>
<name></name>
<info><![CDATA[some info]]></info>
</workOfArt>
</worksOfArt>
</artgallery>
请指教:我在这里的方向正确吗?因为getVisitableChildren()
界面对我来说有点古怪。我是否应该完全放弃访问者模式并采取不同的方法?
谢谢。