采取菲利普建议的更进一步,试试这个。
给定类 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
从堆栈中弹出。这可以让您递归处理树,同时始终可以访问父链。