I have a use case with 7-8 if else. Sample use case:
String type;
List < Entity > entityList;
if (type.equals(\"A\")) {
ClassA a = new ClassA();
A factory implementation could look like this:
public class WidgetFactory {
public static void main(String[] args) {
String type = "A";
List entityList = new ArrayList<>();
Widget widget = WidgetFactory.createWidget(type);
widget.performTask();
for (Entity e : entityList) {
widget.performTaskOnEntity(e);
}
}
private static Widget createWidget(String type) {
switch (type) {
case "A":
return new ClassA();
case "B":
return new ClassB();
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
}
private interface Widget {
void performTask();
void performTaskOnEntity(Entity entity);
}
private static class ClassA implements Widget {
public void performTask() { }
public void performTaskOnEntity(Entity entity) { }
}
private static class ClassB implements Widget {
public void performTask() { }
public void performTaskOnEntity(Entity entity) { }
}
private static class Entity {
}
}