I am trying to understand factory pattern.If there are many implementation then my factory pattern will have lot of if else or switch cases. And also every time I introduce a new implementation i should change my factory code
Like in below examples if lets assume dog duck are implementing Pet interface like tomorrow if many animals implement pet interface my factory frows long with lot of if else else if code or switch case. Is there any way to solve this with bringing more dynamic approach?
package com.javapapers.sample.designpattern.factorymethod;
//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {
public Pet getPet(String petType) {
Pet pet = null;
// based on logic factory instantiates an object
if ("bark".equals(petType))
pet = new Dog();
else if ("quack".equals(petType))
pet = new Duck();
return pet;
}
If the animals grows
if ("bark".equals(petType))
pet = new Dog();
else if ("quack".equals(petType))
pet = new Duck();
else if ("mno".equals(petType))
pet = new MNO();
else if ("jkl".equals(petType))
pet = new JKL();
else if ("ghi".equals(petType))
pet = new GHI();
else if ("def".equals(petType))
pet = new DEF();
......
else if ("abc".equals(petType))
pet = new ABC();
return pet
I think there is a dynamic approach:
Map<String, Class<? extends Pet>>
map.get(pet).newInstance
( you'd have to check for nulls, of course)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With