本着非循环访问者模式的精神,将访问者分成子类特定的访问者。请注意,您仍然需要类型检查,但它包含在被访问的类型中:
以下是访问者界面:
interface IVisitor {
}
interface IRouterVisitor extends IVisitor {
void visit(Router router);
}
interface INetworkCardVisitor extends IVisitor {
}
interface IWirelessNetworkCardVisitor extends INetworkCardVisitor {
void visit(WirelessNetworkCard card);
}
interface IWiredNetworkCardVisitor extends INetworkCardVisitor {
void visit(WiredNetworkCard card);
}
具体的访问者将如下所示:
class WiredVisitor implements IWiredNetworkCardVisitor, IRouterVisitor {
// ...
}
class WirelessVisitor implements IWirelessNetworkCardVisitor, IRouterVisitor {
// ...
}
和访问的对象:
interface INetworkElement {
void accept(IVisitor visitor);
}
class Router implements INetworkElement {
@Override
public void accept(IVisitor visitor) {
if (visitor instanceof IRouterVisitor) {
((IRouterVisitor)visitor).visit(this);
}
}
}
interface INetworkCard extends INetworkElement {}
class WiredNetworkCard implements INetworkCard {
@Override
public void accept(IVisitor visitor) {
if (visitor instanceof IWiredNetworkCardVisitor) {
((IWiredNetworkCardVisitor)visitor).visit(this);
}
}
}
class WirelessNetworkCard implements INetworkCard {
@Override
public void accept(IVisitor visitor) {
if (visitor instanceof IWirelessNetworkCardVisitor) {
((IWirelessNetworkCardVisitor)visitor).visit(this);
}
}
}
在这些类型检查中,如果类型不是预期的类型,您也可以抛出错误,这取决于您希望在这种情况下发生什么。