Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Creational Patterns
Lessons in this course (18)

3. Abstract Factory

IntermediateMediumLesson 3 of 18

Create families of related objects without naming concrete classes.

csharp
public interface IUiFactory { IButton CreateButton(); ITextBox CreateTextBox(); }
public class LightThemeFactory : IUiFactory { public IButton CreateButton() => new LightButton(); public ITextBox CreateTextBox() => new LightTextBox(); }
public class DarkThemeFactory : IUiFactory { public IButton CreateButton() => new DarkButton(); public ITextBox CreateTextBox() => new DarkTextBox(); }

// e.g. ADO.NET: DbProviderFactory creates matching DbConnection, DbCommand, DbParameter for SQL Server / Oracle / SQLite
DbProviderFactory f = SqlClientFactory.Instance;
using DbConnection conn = f.CreateConnection()!;
using DbCommand cmd = f.CreateCommand()!;

Factory Method = one product via inheritance; Abstract Factory = a family of products via composition.