Java – factory pattern dynamic method
I'm trying to understand the factory model If there are many implementations, there will be many switch cases in my factory mode And every time I introduce a new implementation, I should change my factory code
Like the following example, let's assume that dogs and ducks are implementing the pet interface. If many animals implement the pet interface, my factory will take a long time. If there are other code or switch cases, tomorrow Is there any way to solve this problem with more dynamic methods?
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; }@H_301_5@如果动物生长
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@H_301_5@Solution
I think there is a dynamic approach:
>In your factory, you need a map < < string, class & extended pet > > > in the static constructor of each class, it extends pet and registers it with such a map. > Than creating a class will just map get(pet). Newinstance (of course, you must check null)