我有一个复合设计模式的表达:
interface TreeExpression{
void accept(Visitor visitor);
}
abstract class Operator{
TreeExpression childA;
TreeExpression childB;
Operator(TreeExpression a, TreeExpression b){
this.childA = a;
this.childB = b;
}
}
class PlusTreeExpression extends Operator implements TreeExpression{
public PlusTreeExpression(TreeExpression a, TreeExpression b) {
super(a, b);
}
public void accept(Visitor visitor) {
this.childA.accept(visitor);
visitor.visit(this);
this.childB.accept(visitor);
}
}
class MultiplyTreeExpression extends Operator implements TreeExpression{
public MultiplyTreeExpression(TreeExpression a, TreeExpression b) {
super(a, b);
}
public void accept(Visitor visitor) {
this.childA.accept(visitor);
visitor.visit(this);
this.childB.accept(visitor);
}
}
class IntegerNode implements TreeExpression{
Integer value;
IntegerNode(int v){
this.value = v;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
和访问者从表达式中获取字符串:
interface Visitor{
void visit(PlusTreeExpression tree);
void visit(MultiplyTreeExpression tree);
void visit(IntegerNode node);
}
class PrintVisitor implements Visitor{
public StringBuffer result = new StringBuffer();
public void visit(IntegerNode node) {
result.append(node.value);
}
public void visit(PlusTreeExpression tree) {
result.append("+");
}
public void visit(MultiplyTreeExpression tree) {
result.append("*");
}
这个访问者有效,现在我正在尝试让访问者进行评估表达式,但在这里我遇到了问题。我尝试了几种方法来做到这一点,但我不知道如何在不更改现有代码的情况下从子树中获取价值。