我正在写一个使用访客模式的翻译。我有访问者界面,其中包含访问语法的所有表达式和语句的方法。以下是两个例子:
public interface Visitor {
visitExpressionBinary(ExpressionBinary expressionBinary);
visitStatementSleep(StatementSleep statementSleep);
}
根据访问者的具体实现,我想以不同的方式返回不同的类型。例如:
public VisitorA implements Visitor {
int visitExpressionBinary(ExpressionBinary expressionBinary) { ... }
void visitStatementSleep(StatementSleep statementSleep) { ... }
}
public VisitorB implements Visitor {
Expression visitExpressionBinary(ExpressionBinary expressionBinary) { ... }
Statement visitStatementSleep(StatementSleep statementSleep) { ... }
}
我该如何实现这种行为?我想要像这样实现我的访客:
public interface Visitor <V,W> {
V visitExpressionBinary(ExpressionBinary expressionBinary);
W visitStatementSleep(StatementSleep statementSleep);
}
并实施这样的具体访问者:
public VisitorA implements Visitor<Integer, Void> {
Integer visitExpressionBinary(ExpressionBinary expressionBinary) { ... }
Void visitStatementSleep(StatementSleep statementSleep) { ... }
}
public VisitorB implements Visitor<Expression, Statement> {
Expression visitExpressionBinary(ExpressionBinary expressionBinary) { ... }
Statement visitStatementSleep(StatementSleep statementSleep) { ... }
}
这是一个很好的Java编程吗?谢谢!