# Creational Design Patterns

Creational patterns deal with **object creation mechanisms** — abstracting instantiation so
that systems remain flexible about *what* gets created, *who* creates it, and *how*.

## The 7 Creational Patterns

| Pattern | Intent | Complexity | Frequency |
|---|---|---|---|
| [Factory Method](factory.md) | Defer instantiation to subclasses via a creator method | Low | Very High |
| [Abstract Factory](abstract-factory.md) | Create families of related objects without concrete classes | Medium | High |
| [Builder](builder.md) | Construct complex objects step-by-step with a fluent API | Medium | High |
| [Prototype](prototype.md) | Clone existing objects instead of building from scratch | Low | Medium |
| [Singleton](singleton.md) | Ensure exactly one instance exists globally | Low | High |
| [Object Pool](object-pool.md) | Reuse expensive objects from a pre-allocated pool | Medium | Medium |
| [Dependency Injection](dependency-injection.md) | Supply dependencies externally instead of creating them internally | Low | Very High |

## When to Use Which

```
Need to create one of several related types at runtime?
  --> Factory Method

Need to create families of related objects that must be consistent?
  --> Abstract Factory

Need to construct a complex object with many optional parts?
  --> Builder

Need to duplicate an existing configured object?
  --> Prototype

Need exactly one shared instance (and DI is not an option)?
  --> Singleton

Need to reuse expensive-to-create objects (connections, threads)?
  --> Object Pool

Need to decouple a class from the specific implementations it uses?
  --> Dependency Injection
```

## Comparison Matrix

| Concern | Factory | Abstract Factory | Builder | Prototype | Singleton | Object Pool | DI |
|---|---|---|---|---|---|---|---|
| Hides concrete type | Yes | Yes | Partially | No | N/A | N/A | Yes |
| Supports families | No | Yes | No | No | No | No | Yes |
| Fluent API | No | No | Yes | No | No | No | No |
| Avoids `new` | Yes | Yes | Yes | Yes | No | Yes | Yes |
| Thread-safety concern | Low | Low | Low | Medium | High | High | Low |
| Testability | Good | Good | Good | Good | Poor | Good | Excellent |

## Key Principle

> **Favor composition over inheritance, and injection over creation.**
>
> Most modern codebases rely heavily on **Factory Method** and **Dependency Injection**
> as their primary creational strategies. Use others when their specific strengths
> match a concrete problem.

## Language Idioms

- **Python**: Factories are often plain functions; Singletons use `__new__` or module-level instances; DI via constructor args.
- **Go**: Factories are `NewXxx()` functions; Singletons use `sync.Once`; no classes so Builder uses method chaining on structs.
- **JavaScript**: Module exports naturally singleton; Factories return plain objects or class instances; Prototype via `Object.create` or manual clone.
