Reputation: 775
Suppose I have 100 types of objects to be created and for that I have exposed a factory to create these objects. For the creation of these objects, I have 100's of if, else if
.
In these kind of scenarios where many types of objects are to be created (of course you want to create one object per class), is there a better creational pattern?
Upvotes: 1
Views: 1151
Reputation: 393841
If there's a single criteria by which you choose which class to instantiate, you can create a Map<CriteriaType,Class>
which maps a criteria to the class that should be instantiated.
Then, your 100 if else-ifs would be reduced to a single map.get(criteria).newInstace()
.
If you have multiple criteria, you can try to arrange them in a hierarchy, and then you can have a multi-dimensional map, such as Map<CriteriaType1,Map<CriteriaType2,Class>>
. Then you'll have to go down the hierarchy to find the class to be instantiated.
Upvotes: 10