Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

factory pattern dynamic approach

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
like image 852
constantlearner Avatar asked Aug 14 '13 15:08

constantlearner


1 Answers

I think there is a dynamic approach:

  1. In your factory you need a Map<String, Class<? extends Pet>>
  2. In static constructor of every class, which extends Pet, register it with such map.
  3. Than creating a class will be just map.get(pet).newInstance ( you'd have to check for nulls, of course)
like image 116
Eugene Ryzhikov Avatar answered Oct 31 '22 15:10

Eugene Ryzhikov