Factory Pattern

How it works

Factory Pattern
How it works
  1. Input arrives
  2. Core component processes
  3. Result produced
  4. Observe and iterate

Overview

Use factories when you need to create families of related objects without tightly coupling to concrete classes.

Learning Objectives

🎯 Understanding Object Creation Patterns

Master the fundamental concept of abstracting object creation to promote loose coupling and flexible design

🔧 Implementation Techniques

Learn different factory pattern variations including Simple Factory, Factory Method, and Abstract Factory

⚡ Design Benefits

Understand how factories enable runtime object creation decisions and support the Open/Closed Principle

Real-World Examples

🚗 Vehicle Manufacturing System

Tesla's production line creates different vehicle models (Model S, Model 3, Model X) based on customer orders without exposing specific assembly processes

Benefit: 40% faster new model integration

📱 UI Component Libraries

React component libraries like Material-UI use factory functions to create themed components with consistent styling across applications

Benefit: 90% reduction in theme configuration code

🌐 Database Connection Pools

Connection factories in enterprise applications create appropriate database connections (MySQL, PostgreSQL, MongoDB) based on configuration

Benefit: 60% easier database migration

🔐 Authentication Systems

OAuth providers use factories to create authentication handlers for different services (Google, Facebook, GitHub) with unified interfaces

Benefit: 75% faster integration of new providers

How it works

  1. Define a Product interface
  2. Implement ConcreteProduct variants
  3. Provide a Factory that returns Product
  4. Clients use Factory, unaware of the concrete classes

Code example

A simple factory that creates a Vehicle by kind without exposing constructors:
interface Vehicle { deliver(): string }

class Truck implements Vehicle { deliver(): string { return 'Deliver by land' } }
class Ship implements Vehicle { deliver(): string { return 'Deliver by sea' } }

function createVehicle(kind: string): Vehicle {
  if (kind === 'truck') return new Truck();
  if (kind === 'ship') return new Ship();
  throw new Error('Unknown kind: ' + kind);
}

var v = createVehicle('truck');
// v.deliver() -> 'Deliver by land'

Implementation Notes

  • Use Simple Factory for basic object creation with conditional logic
  • Apply Factory Method when subclasses need to decide which objects to create
  • Choose Abstract Factory for creating families of related objects
  • Consider using dependency injection containers in larger applications
  • Combine with Builder pattern for complex object construction scenarios

Best Practices

  • Keep factory methods focused on single responsibility of object creation
  • Use enums or constants instead of string literals for factory parameters
  • Implement proper error handling for unsupported object types
  • Consider caching or pooling objects when creation is expensive
  • Document the lifecycle and ownership of created objects clearly

Common Pitfalls

  • Creating overly complex factories that violate Single Responsibility Principle
  • Using factories when simple constructors would suffice, adding unnecessary abstraction
  • Forgetting to handle memory cleanup in factories that manage object lifecycle
  • Mixing business logic with object creation logic in factory methods
  • Not providing clear interfaces causing tight coupling between factory and products