I am having a class named DBObject which returns two different class objects.If the input string is water it returns object1 else object2.
My requirement is , now it it is returning objects based on if else…but in future some more objects will be added. So, instead of using elseif which makes code static, is there any dymanic way to return the class objects?
I mean can i use any java design pattern in this scenario?
code:
if(str=="water")
return new object1()
else if...
return new object3()
else if...
return new object4()
else if...
return new object5()
else if...
return new object6()
else
return new object2()
You’re talking about implementation level here, not design level. For implementation you need Java Reflection, which you can use like:
On design level Abstract Factory is the closest pattern.