I have various types of events as shown below. In general I have more events.
EventA
EventB
EventC
EventD
Below is the code where I will get each event types:
public void run() {
try {
while (!closed.get()) {
ConsumerRecords records = consumer.poll(10000);
// Handle new records
for (ConsumerRecord<String, String> record : records) {
GenericRecord payload = decoder.decode(record.value());
String eventType = String.valueOf(payload.get("eventType"));
String eventHolder = String.valueOf(payload.get("eventMapHolder"));
Map<String, String> eventMap = parseStringToMap(eventHolder);
// here eventType will "EventA", "EventB" and so on
// pass eventType to get the individual factory for that event type
// and then pass eventMap to a particular method of that factory class which calls appropriate Query method.
}
}
} catch (Exception e) {
// log error
}
}
For each event, I need to perform different database queries but for most of them atleast, I need to perform one database query which is common for all of them. For example:
EventA -----> QueryA, QueryB
EventB -----> QueryA
EventC -----> QueryA, QueryC
EventD -----> QueryA, QueryD
So for "EventA", QueryA method will be executed first and then QueryB will be executed. Similarly for "EventB", QueryA will be executed and so on. As you can see, QueryA is the common method which will be called for all the event type but for rest of them they have their own queries method to be executed.
All the query method takes Map parameter and returns same as well.
Question:
Which design pattern I should use for this kind of problem? I want to avoid using if/else or switch here bcoz in general I have lot of event types so thinking of making an individual factory for them which we can load it at runtime dynamically by passing eventType value.
I know all the eventType beforehand so I can statically initialize all the factories by putting it in a map and then once the eventType comes while we are running the code, I can load individual factories from the map.
How can I use abstract factory pattern here to accomplish this if this is the right design pattern for this problem? I want to pass "eventType" as the key to a factory which will return instance of that event type. So let's say I will pass "EventA" to the factory and then it will return factory class for "EventA" and then we will call a particular method on that class which internally calls QueryA method and then we call QueryB method. And Similarly for other event types.
Aucun commentaire:
Enregistrer un commentaire