samedi 7 novembre 2020

OOP Java Design Pattern for the following Scenario

I have the following scenario I'm struggling to come up with an elegant solution for...

  1. I have an endpoint that is subscribed to a pub-sub topic, this particular pub-sub topic has 10 different type of notifications/messages it can read.

The following is the interface

public interface Handler {
    void handle(String msg);
}

The following is an Event Handler

public class TeamMemberHandler implements Handler {
    @Override
    public void handle(String msg) {

    }
}

The following is the pubsub listener class, where I want to move away from having 10 different switch cases for each event.

public class PubSubListener {

    // garbage quick example


    @PostMapping("/pubsublistener")
    private String pubsublistener(@RequestBody String msg) {

        Map<String, Object> map = new Gson.fromJson(msg, HashMap.class);

        String event = (String)map.get("rootElement");

        // want to move away from this
        switch(event){
            case "1":
                break;
            .
            .
            .

            case "10":
                break;

            default:
                break;
        }

    }
}

I would like to do something along the following... where I have a map of every single event type in String, and the Handler associated with it.

However, it is not possible to do handler.handle() in the below code. How can I go about achieving this?

        Map<String, Class<? extends Handler>> handlers = new HashMap<>();
        handlers.put("TeamMemberEvent",  TeamMemberHandler.class);
        handlers.put("OtherTypeOfEvent", OtherTypeOfHandler.class);

        Class<? extends Handler> handler = handlers.get(event);
        handler.handle(msg);

Aucun commentaire:

Enregistrer un commentaire