design patterns 6 min read 2024-12-27

Factory Pattern: Creating Objects the Right Way

Learn how the Factory pattern provides a way to create objects without specifying the exact class of object that will be created.

Java Design Patterns Creational Patterns Factory

Factory Pattern: Creating Objects the Right Way

The Factory pattern is a creational design pattern that provides an interface for creating objects without specifying their exact classes.

What is the Factory Pattern?

The Factory pattern uses a factory method to create objects without exposing the instantiation logic to the client. The client refers to the newly created object through a common interface.

Types of Factory Patterns

1. Simple Factory

public class SimpleFactory {
    public static Product createProduct(String type) {
        switch (type) {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new IllegalArgumentException("Unknown product type");
        }
    }
}

2. Factory Method Pattern

// Product interface
interface Product {
    void use();
}

// Concrete Products
class ConcreteProductA implements Product {
    public void use() {
        System.out.println("Using Product A");
    }
}

class ConcreteProductB implements Product {
    public void use() {
        System.out.println("Using Product B");
    }
}

// Creator abstract class
abstract class Creator {
    public abstract Product createProduct();
    
    public void someOperation() {
        Product product = createProduct();
        product.use();
    }
}

// Concrete Creators
class ConcreteCreatorA extends Creator {
    public Product createProduct() {
        return new ConcreteProductA();
    }
}

class ConcreteCreatorB extends Creator {
    public Product createProduct() {
        return new ConcreteProductB();
    }
}

3. Abstract Factory Pattern

// Abstract Factory
interface AbstractFactory {
    ProductA createProductA();
    ProductB createProductB();
}

// Concrete Factories
class ConcreteFactory1 implements AbstractFactory {
    public ProductA createProductA() {
        return new ConcreteProductA1();
    }
    
    public ProductB createProductB() {
        return new ConcreteProductB1();
    }
}

When to Use?

Benefits

Real-World Examples

Conclusion

The Factory pattern is essential for creating flexible, maintainable code. Choose the right variant based on your specific needs.

← Back to Blog