jeudi 1 avril 2021

Simple factory VS Factory Method (why use factory method at all)

Im trying to learn patterns and got to Factory, I understand the concept of simple factory and factory method, I know how they work, what I cant understand is what is the benefit of factory method over the simple factory. Example:

//We have our clients here
public class Animal {}
public class Dog extends Animal{}
public class Cat extends Animal{}

In a simple factory we will have this thing:

public Animal getAnimal(String type) {
    switch (type) {
    case "cat": 
      return new Cat;
    case "dog":
      return new Dog;
    }
    return null;
}

Now we go for the factory method:

public abstract class AnimalFactory {
   //Some common animal code here
}
public class DogFactory extends AnimalFactory{
   public Animal getAnimal(){
      //some logic
      return new Dog;
   }
}
public class CatFactory extends AnimalFactory{
   public Animal getAnimal(){
      //some logic
      return new Cat;
   }
}

So here comes the interesting part, for the factory method we will need to use polymorphism but we will still need to instantiate depending on what type we need so I imagine we will have something like this:

public Animal getAnimal(String type) {
    AnimalFactory animalFactory;
    switch (type) {
    case "cat": 
      animalFactory = new CatFactory();  //polymorphism     
      return animalFactory.getAnimal();
    case "dog":
       animalFactory = new DogFactory();  //polymorphism     
      return animalFactory.getAnimal();
    }
    return null;
}

So as far as I know the main idea behing design patterns is to make code more reusable and easier to extend, so imagine we need to add a new animal, say a Parrot. In both cases we create the Parrot class that extends the Animal class and in both cases we will have to go into that switch statement and add a new case "Parrot" For the simple factory we will just instantiate new Parrot directly and for the factory method we will instantiate the ParrotFactory. My question is what is the difference and why do we need the factory method pattern?

The only benefit I can see is that in the factory method you can define common logic for the factories that will extend it (is that it ?)

Aucun commentaire:

Enregistrer un commentaire