Return to site

What is the Factory pattern in Java?

· java,video

The Factory pattern is a creational design pattern that provides a way to create objects without exposing the creation logic to the client.

Instead, the client calls a factory method that returns the desired object.

🏭 Why use it?

- Centralizes object creation logic

- Makes code easier to maintain and extend (open/close principle, hide complexity...)

- Reduces coupling between the client and concrete classes (abstraction, easier testing, DI, runtime selection..)

🛠️ Example:

class ShapeFactory {
 public Shape getShape(String type) {
 return switch (type) {
 case "circle" -> new Circle();
 case "square" -> new Square();
 default -> null;
 };
 }
}

Usage:

Shape shape = new ShapeFactory().getShape("circle");

💡 Great when you have multiple related classes and want a clean way to decide which one to instantiate.