Creational Patterns
Overview
Creational patterns manage object creation in a flexible and controlled way. They reduce coupling between object usage and instantiation.
Common Creational Patterns
- Factory Method
- Abstract Factory
- Builder
- Singleton
- Prototype
classDiagram
class Client
class Factory
class Product
Client --> Factory : requests
Factory --> Product : creates
Practical Example - Builder
public sealed class Report
{
public string Title { get; init; } = string.Empty;
public List<string> Sections { get; init; } = new();
}
public sealed class ReportBuilder
{
private readonly Report _report = new();
public ReportBuilder SetTitle(string title)
{
_report.Title = title;
return this;
}
public ReportBuilder AddSection(string section)
{
_report.Sections.Add(section);
return this;
}
public Report Build() => _report;
}
Builder helps when objects need many optional fields with readable construction.
Production Guidance
- Use factories for environment-specific dependencies
- Use builders for complex object assembly
- Reserve singleton for truly shared stateless components
Common Pitfalls
- Overusing singleton and creating hidden global state
- Adding factories where constructors are enough
- Creating abstract factories without multiple product families
Key Takeaways
- Creational patterns improve flexibility of object creation.
- Builder and factory patterns are frequently useful in business systems.
- Pattern choice should follow concrete complexity, not preference.