Java – typesafe delegation without instanceof
•
Java
I have a service program:
filter(List<Criterion> criteria);
Is there a good way to internally assign method calls to the type safe implementation of specific criteria without involving instanceof and without confusing the API
I like the following things (although nature doesn't work):
filter(List<Criterion> criteria) {
for (Criterion c : criteria) {
dispatch(c);
}
}
dispatch(FooCriterion c) {...}
dispatch(BarCriterion c) {...}
Solution
Although it may be considered chaotic, a visitor like pattern can be used (using the dual scheduling principle):
public class Dispatcher {
void dispatch(FooCriterion foo) { .. }
void dispatch(BarCriterion bar) { .. }
}
class FooCriterion implements Criterion {
void visit(Dispatcher d) {
d.dispatch(this);
}
}
Dispatcher d = new Dispatcher();
for (Criterion c : criteria) {
c.visit(d);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
