Understanding the Factory Pattern in Java
September 14, 2023
Understanding the Factory Pattern in Java
The Factory Pattern is one of the most commonly used design patterns in Java. It's a creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Why Use the Factory Pattern?
- Decoupling: It decouples the implementation of the product from its use
- Encapsulation: It encapsulates object creation logic
- Flexibility: Makes adding new types easier without changing existing code
Simple Factory Example
// Product interface interface Product { void operation(); } // Concrete products class ConcreteProductA implements Product { @Override public void operation() { System.out.println("ConcreteProductA operation"); } } class ConcreteProductB implements Product { @Override public void operation() { System.out.println("ConcreteProductB operation"); } } // Factory class class ProductFactory { public static Product createProduct(String type) { if (type.equals("A")) { return new ConcreteProductA(); } else if (type.equals("B")) { return new ConcreteProductB(); } return null; } } // Client code public class Main { public static void main(String[] args) { Product productA = ProductFactory.createProduct("A"); productA.operation(); Product productB = ProductFactory.createProduct("B"); productB.operation(); } }
When to Use the Factory Pattern
The Factory Pattern is particularly useful when:
- A class cannot anticipate the type of objects it needs to create
- A class wants its subclasses to specify the objects it creates
- You want to localize the knowledge of which class gets created
By implementing the Factory Pattern, you can make your code more flexible, maintainable, and less coupled.