I need to collect statistics during an algorithm. To not mix the statistical code with the algorithm code too much, I'd like to decouple that by publishing "statistical events" that can then be consumed where appropriate.

For that I'd like a lightweight implementation using an Enum instead of an interface. Code speaks more than a thousand words, so let me quickly whip up an example:

public class ObjectThatHasEvents {

    private Map< StatisticEvent, List<Consumer> > registeredObserver = ...

    public enum StatisticEvent{

    public void registerObserver(StatisticEvent event, Consumer callback) {
         //add the consumer to the map on the correct event

    private void triggerEvent(StatisticEvent event, Integer valueForConsumption) 
        registeredObserver.get(event).forEach(i -> i.consume(valueForConsumption)

    //all the other necessary stuff here...


Advantage: It's quite easy to add a new event, you add a new eventType to the enum, publish it where appropriate, and register to it somewhere else in the code.

Disadvantage: I'm banking on the fact that the callback is always a single param consumer. If a situation arises where that ain't the fact, the whole system could come crashing down or require serious hacking. I might be able to cheat this a bit with generic callbacks, but that would require some thought, ugly hacks and probably is non-obvious.

The alternative is having an statistical interface just for this class, that needs to then be implemented with all methods etc., possibly overswarming the class with many many methods that basically always do the same thing.

Is this approach viable, or am I missing something entirely?

| improve this question | | | | |

I think it depends on what an event means to you. If it is just a signal, enum should be fine. Otherwise you may implement an abstract Event or Interface and concrete Events. With that adding a new Event type is as simple as creating a sub class and each Event type may contain different type of data you want to send to the observer.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.