Factory Pattern

A creational design pattern that provides an interface for creating objects without explicitly specifying their exact classes.

Factory Pattern

The Factory Pattern is a fundamental design pattern that provides a scalable approach to object creation in object-oriented programming. It encapsulates the instantiation logic and allows for flexible object creation without tightly coupling code to specific classes.

Core Concepts

Basic Structure

  • A factory interface or abstract class that declares the creation method
  • Concrete factory implementations that produce specific object types
  • Product interfaces that define what the created objects can do
  • Concrete product implementations

Types of Factory Patterns

  1. Simple Factory

    • Not technically a design pattern but a common programming idiom
    • Single factory class with a method that creates objects
    • Uses conditional logic to determine which object to create
  2. Factory Method Pattern

    • Defines an interface for creating objects
    • Allows subclasses to alter the type of objects created
    • Promotes loose coupling between creator and products
  3. Abstract Factory Pattern

    • Creates families of related objects
    • Provides an interface for creating variants of objects
    • Useful for ensuring system consistency across product families

Benefits

Implementation Example

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

// Concrete products
class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof!");
    }
}

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

// Factory
class AnimalFactory {
    public Animal createAnimal(String type) {
        if (type.equals("dog")) return new Dog();
        if (type.equals("cat")) return new Cat();
        throw new IllegalArgumentException("Unknown animal type");
    }
}

Common Use Cases

Best Practices

  1. Use factories when:

    • Object creation involves complex logic
    • You need to maintain object creation consistency
    • The system requires runtime flexibility in object creation
  2. Avoid when:

    • Object creation is simple and straightforward
    • The additional abstraction would add unnecessary complexity

Related Patterns

The Factory Pattern often works in conjunction with other design patterns:

Anti-patterns to Avoid

  • Over-complicating simple object creation
  • Creating factories for every class
  • Mixing business logic with factory logic
  • Ignoring SOLID principles in factory implementation

The Factory Pattern remains one of the most widely used design patterns in software development, providing a robust foundation for flexible and maintainable object creation systems.