Advanced OOP
Factory Pattern
Object creation patterns and factory methods
Interview: Design patterns — tests understanding of creational patterns, polymorphic construction, and dependency inversion
The Factory pattern provides a way to create objects without specifying the exact class to instantiate. The client code asks a factory for an object, and the factory decides which class to instantiate. This promotes loose coupling and makes code easier to extend with new types.
Types of Factory Patterns
- Simple Factory: A function/class that creates objects based on input
- Factory Method: A method in a base class that subclasses override to create objects
- Abstract Factory: A family of related factory methods
- Registry Pattern: Classes register themselves, factory looks them up
Benefits
- Decouples object creation from usage
- Easy to add new types without changing client code
- Centralizes creation logic (validation, caching, logging)
Interview Tip
Know the difference between Factory Method and Abstract Factory. Factory Method is a single method; Abstract Factory is an object with multiple factory methods. In Python, @classmethod is the natural Factory Method.
Use Cases
Creating objects based on configuration or user input (parsers, serializers)
UI frameworks: platform-specific widgets from abstract dialogs
Plugin systems: auto-registering handlers/formats
Database adapters: creating appropriate connection based DB type
Game development: spawning entities by type name
Common Mistakes
Over-engineering simple cases — a dictionary dispatch is often enough
Not validating factory input (unknown types should raise clear errors)
Hardcoding class imports in factory (defeats the purpose of loose coupling)
Forgetting that Python's @classmethod is already a natural factory method
Using Abstract Factory when a simple function would suffice