Eigentlich soll ja auch das gehen,
Operation.contains (new Zahlenfolge(1,5,2,8), 2)) ==> truegeht aber nicht, weil der Rückgabewert bisher auf int fixiert ist.
Lösung der Rückgabetyp wird ein Parameter:
class Zahlenfolge { ...
public interface Visitor<R> {
R empty();
R nonempty(R previous_result, int element);
}
}
Behandlung eines Besuchers
class Zahlenfolge { ...
public <R> R visit(Visitor<R> v) {
R accu = v.empty();
for (int x : this.contents) {
accu = v.nonempty(accu, x);
}
return accu;
}
}
Beispiel:
public class Operation {
static boolean contains (Zahlenfolge f, int x) {
return f.visit(new Zahlenfolge.Visitor<Boolean>() {
public Boolean empty() { return false; }
...
}
}