Search code examples
javadelegation

Typesafe delegation without instanceof


I have a service routine:

filter(List<Criterion> criteria);

Is there a good way to internally dispatch the method call to a typesafe implementation of a specific Criteria without involving instanceof and without cluttering the API.

I'd like something like the following (which naturally doesn't work though):

filter(List<Criterion> criteria) {
   for (Criterion c : criteria) {
       dispatch(c);
   }
 }

dispatch(FooCriterion c) {...}
dispatch(BarCriterion c) {...}

Solution

  • Although it might be viewed as cluttering, something like the Visitor pattern can be used (using the principle of double-dispatch):

    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);
    }