Explain the Factory Method Pattern.

Beginner

Answer

The Factory Method pattern creates objects without specifying their exact classes. It defines an interface for creating objects, but lets subclasses decide which class to instantiate.

Example:

interface Animal {
    void makeSound();
}

abstract class AnimalFactory {
    abstract Animal createAnimal();
}

class DogFactory extends AnimalFactory {
    Animal createAnimal() {
        return new Dog();
    }
}

Benefits:

  • Loose coupling between creator and concrete products
  • Easy to extend with new product types
  • Follows Open/Closed Principle