I'm trying to find an elegant OOP solution for the following problem.
Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).
A basic assumption is that we can't decorate the POJOs with appropriate handlers, since we don't control their generation, and receive the collection as is. Thus, any mechanism for this falls into the same trap. However, item 3 stil deals with this possibility.
There are some possible solutions, some very ugly, some more elegant but complicated:
- The obvious solution, and the ugliest, is using instanceOf operators to pass POJO to handler.
- A slightly better modification of 1, is to use a chain of responsibility for this, with chained dispatcher, so that new types just need a new dispatcher. However, each dispatcher stills needs instanceOf.
- Create enhanced objects, not POJOS, where each object holds a reference to its handler. This creates a coupling between POJO and our processor.
- Create (I know how to do this correctly in Java) a dispatcher service which registers handlers to the specific event class, and use generics (Typesafe container, as in effective java) to dispatch event to handler.
4 is the most elegant, but I was wondering if there are any better ideas.