当你使用访客模式时,以及你需要在访客方法中找到一个变量时,如何去做?
我看到两种做法。 第一类使用匿名类别:
// need a wrapper to get the result (which is just a String)
final StringBuild result = new StringBuilder();
final String concat = "Hello ";
myObject.accept(new MyVisitor() {
@Override
public void visit(ClassA o)
{
// this concatenation is expected here because I ve simplified the example
// normally, the concat var is a complex object (like hashtable)
// used to create the result variable
// (I know that concatenation using StringBuilder is ugly, but this is an example !)
result.append(concat + "A");
}
@Override
public void visit(ClassB o)
{
result.append(concat + "B");
}
});
System.out.println(result.toString());
Pros & Cons:
- Pros : you do not need to create a class file for this little behavior
- Cons : I don t like the "final" keyword in this case : the anonymous class is less readable because it calls external variables and you need to use a wrapper to get the requested value (because with the keyword final, you can t reassign the variable)
另一种做法是进行外部访问:
public class MyVisitor
{
private String result;
private String concat;
public MyVisitor(String concat)
{
this.concat = concat;
}
@Override
public void visit(ClassA o)
{
result = concat + "A";
}
@Override
public void visit(ClassB o)
{
result = concat + "B";
}
public String getResult()
{
return result;
}
}
MyVisitor visitor = new MyVisitor("Hello ");
myObject.accept(visitor);
System.out.println(visitor.getResult());
Pros & Cons:
- Pros : all variables are defined in a clean scope, you don t need a wrapper to encapsulate the requested variable
- Cons : need an external file, the getResult() method must be call after the accept method, this is quite ugly because you need to know the function call order to correctly use the visitor
你,你在此问题上的做法是什么? 旧方法? 另一种想法?