Search code examples
javadesign-patternsabstract-factory

Design Pattern Need to remove a series of If.. elses in object initialization


I'm writing an application in which there will be multiple departments and for each department there will be separate processing class. Each department and department processing is represented by separate class.

so, now main method in java looks more like series of if else ladder.

Is there any way of making it more flexible so that i can add more departments and their processing classes later without modifying the originally written class much ??

I've read about Abstract Factory patterns but is there any other solution than it ??


Solution

  • The Abstract Factory pattern is probably best suited to the scenario that you described. You will need a heirarchy of Department Processors and a matching heirarchy of Department classes. The Abstract factory will produce a concrete factory for each pair based on some discriminator, process the department for you and return the Department object.

    The rest of your application does not need to be aware of the differences in the creation of the department objects since it will use the FActory to get a department simply passing the appropriate discriminator.

    Adding a new department will require the new department clas, the processor class and updating the factory logic.


    Alternatively, if the structure of the departments are all the same but the processing is different you may consider using something like the Strategy pattern. In this case you have a single Department, but the deccision about processing will be made for the Strategy instead. So the appropriate Strategy is injected into the department and the department's behaviour differs accordingly.