フィリップが提案したことを一歩進めて、これを試してください。
指定されたクラス Widget が親であり、クラス Feature が子階層の基本型です
簡単な使い方:
// widget will have an instance of a Feature subclass from args or config, etc
Widget theWidget = new Widget(args);
// create and configure visitor
Visitor theVisitor = new Visitor();
theVisitor.prop1 = x;
theVisitor.prop2 = y;
theVisitor.prop3 = z;
theWidget.visit(theVisitor);
ウィジェット (親クラス):
class Widget
{
Feature _childFeature;
void visit(Visitor visitor)
{
visitor.beginAccept(this);
childFeature.visit(visitor);
visitor.endAccept();
}
}
フィーチャ クラスの階層:
abstract class Feature
{
abstract void visit(Visitor visitor);
}
class Sunroof extends Feature
{
void visit(Visitor visitor)
{
visitor.accept(this);
}
}
class BulletProof extends Feature
{
void visit(Visitor visitor)
{
visitor.accept(this);
}
}
class GoldPlated extends Feature
{
void visit(Visitor visitor)
{
visitor.accept(this);
}
}
親と子の両方を使用する具体的なビジター:
class ExampleVisitor extends Visitor
{
private _widgetInProcess;
void beginAccept(Widget w)
{
_widgetInProcess = w;
}
void accept(Sunroof feature)
{
// do work based on both _widgetInProcess and type-specific feature
}
void accept(BulletProof feature)
{
// do work based on both _widgetInProcess and type-specific feature
}
void accept(GoldPlated feature)
{
// do work based on both _widgetInProcess and type-specific feature
}
void endAccept()
{
_widgetInProcess = null;
}
}
beginAccept
スタックにプッシュすると、さまざまなaccept
メソッドがスタックをピークして親コンテキストを取得し、スタックendAccept
からポップするツリー モデルのユースケースも視覚化できます。これにより、常に親チェーンにアクセスしながら、ツリーを再帰的に処理できます。