mardi 20 juillet 2021

Handler pattern?

I came across several java projects at my company (but this could be done with any OOP language) where we receive an object and depending on some fields we have to do a particular process. To avoid doing a huge list of if/else the following pattern is used :

Create handlers that have a common interface :

public interface IEventHandler {
    boolean support(Event event);
    void handle(Event event);
}

public class Handler1 implements IEventHandler {

    public Handler1() {
    }

    @Override
    public boolean support( Event event ) {
        return event.is1();
    }

    @Override
    public void handle( Event event ) {
        //Do something
    }
}

then you "register the handlers" and loop to execute the action :

List<IEventHandler> handlers = List.of(new Handler1());

for ( final IEventHandler handler : handlers ) {
  if ( handler.support( event ) ) {
    handler.handle( event );
  }
}

I'm pretty sure this is an anti-pattern but I'm not sure how this pattern is called to find better alternatives.

Aucun commentaire:

Enregistrer un commentaire