スカラーメンバーを持ち、同時にメンバー(コレクション)を集約するいくつかのオブジェクトにビジターパターンを適用するのに苦労しています。
これらは私が持っているオブジェクトです:
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ファイルを書き出す具体的なVisitorを作成することが目標です。
<?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()
インターフェースが少し風変わりな感じがするからです。おそらく、ビジターパターンを完全に捨てて、別のアプローチを取るべきでしょうか?
ありがとう。