Factory Method Design Pattern — Java

Ashwani Kumar Dubey
2 min readMar 24, 2023

The Factory Method design pattern is a way of creating objects. In this pattern, instead of creating objects directly using a constructor or a new operator, we use a special method called the factory method.

Factory method design pattern

The factory method acts as a “factory” that creates and returns different types of objects based on the inputs provided to it. For example, if we want to create an object of a particular class, we call the factory method and pass in the type of the object we want. The factory method then creates the object and returns it to us.

Class Diagram

Here is an example for factory method implementation

public interface Animal {
void makeSound();
}

public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}

public class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}

public abstract class AnimalFactory {
public abstract Animal createAnimal(String type);
}

public class ConcreteAnimalFactory extends AnimalFactory {
@Override
public Animal createAnimal(String type) {
if (type.equals("Dog")) {
return new Dog();
} else if (type.equals("Cat")) {
return new Cat();
} else {
throw new IllegalArgumentException("Invalid animal type: " + type);
}
}
}

And this is how you can use the factory to create your objects.

AnimalFactory factory = new ConcreteAnimalFactory();
Animal dog = factory.createAnimal("Dog");
dog.makeSound(); // Output: Woof!

Animal cat = factory.createAnimal("Cat");
cat.makeSound(); // Output: Meow!

This design pattern is useful because it allows us to encapsulate the object creation logic in one place, making our code more modular and flexible. It also helps us to avoid dependencies on specific classes or implementations, and allows us to switch between different object types easily.

Thanks for reading. Hope you like the post.

--

--