🏭

Factory Pattern Guide

Verified

by Community

Covers the factory method and abstract factory design patterns for flexible object creation. Explains when to use each variant, how to implement them in modern languages, and how factories support the open-closed principle.

factorydesign-patterncreational

Factory Pattern Guide

Use factory patterns to encapsulate object creation logic and decouple client code from concrete implementations. Covers simple factory, factory method, and abstract factory with practical examples.

Usage

Ask about which factory variant to use, how to implement factories in your language, or how to refactor direct instantiation to use factories.

Examples

  • "When should I use factory method vs abstract factory?"
  • "Help me implement a factory for creating database connections"
  • "How do I register new types with a factory at runtime?"

Guidelines

  • Use simple factory for straightforward creation with a few types
  • Use factory method when subclasses need to decide which class to instantiate
  • Use abstract factory when you need families of related objects
  • Consider using a registry pattern for extensible factories
  • Factories should not contain business logic beyond object creation