Skip to content

Abstract Factory

Context: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

public interface IButton { void Render(); }
public interface ITextBox { void Render(); }
public class WinButton : IButton { public void Render() => Console.WriteLine("Win Button"); }
public class WinTextBox : ITextBox { public void Render() => Console.WriteLine("Win TextBox"); }
public interface IGUIFactory
{
IButton CreateButton();
ITextBox CreateTextBox();
}
public class WinFactory : IGUIFactory
{
public IButton CreateButton() => new WinButton();
public ITextBox CreateTextBox() => new WinTextBox();
}
// Usage
IGUIFactory factory = new WinFactory();
IButton btn = factory.CreateButton();
btn.Render();

Cross‑platform UI frameworks: Abstract Factory creates platform‑specific controls (buttons, text boxes, windows) without changing client code. For Windows, use WinFactory; for macOS, use MacFactory.

Example: In .NET, System.Data.Common.DbProviderFactory is an abstract factory. Concrete factories like SqlClientFactory create DbConnection, DbCommand, DbDataAdapter for specific databases.