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 {
public Animal createAnimal() {
Animal animal = getAnimal();
animal.pet();
return animal;
}
protected abstract Animal getAnimal();
}
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 ?)
the benefit is it encapsulates the logic to create dogs for example. Any modification about creational of dog only happens on DogFactory (Single Responsibility). It's a good choice when you're going to do any setup about the object, like there are any codes before you return the dog object. If you do it on simple factory it would be messed up and make the method longer. But since on your example it's only do a simple new Dog()
or new Cat()
I prefer simple factory. IMHO