Factory Method

A creational design pattern that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created.

Factory Method Pattern

The Factory Method is a fundamental design pattern that addresses the problem of creating objects without explicitly specifying their exact classes. It's one of the most commonly used creational patterns in object-oriented software development.

Core Concept

At its heart, the Factory Method pattern defines an interface for creating objects but delegates the actual instantiation to subclasses. This creates a layer of abstraction between:

  • The client code that needs an object
  • The actual class of the object being created

Structure

The pattern consists of several key components:

  1. Creator (Factory)

    • Declares the factory method that returns the object
    • May also include default implementation
    • Can contain common code that works with products
  2. Concrete Creator

    • Overrides the factory method to create specific products
    • Implements the creation logic
  3. Product

    • Defines the interface for objects the factory creates
    • Represents the object being created
  4. Concrete Product

    • Specific implementations of the product interface

Benefits

Common Use Cases

  1. Framework Development

    • Creating platform-specific components
    • Plugin architectures
    • Extensible systems
  2. Object Creation Systems

Implementation Example

// Product interface
interface Animal {
    void makeSound();
}

// Creator interface
abstract class AnimalFactory {
    abstract Animal createAnimal();
}

// Concrete implementations
class DogFactory extends AnimalFactory {
    @Override
    Animal createAnimal() {
        return new Dog();
    }
}

Related Patterns

The Factory Method pattern often works in conjunction with:

Best Practices

  1. Keep factories focused and cohesive
  2. Consider using static factory methods for simple cases
  3. Avoid overcomplicating with unnecessary abstraction
  4. Document the intended use cases and limitations

Common Pitfalls

  • Over-engineering simple object creation
  • Creating too many factory classes
  • Mixing business logic with object creation
  • Ignoring SOLID principles in factory implementations

The Factory Method pattern is a cornerstone of flexible and maintainable object-oriented design, providing a powerful way to encapsulate object creation logic while supporting future extensibility.