Creational patterns are concerned with one question: how does an object get built, and how much does the calling code need to know about the concrete type it ends up with?
Factory Method defers which concrete class gets instantiated to a dedicated method, so calling code depends only on an abstraction:
public interface INotifier { void Send(string message); }
public class EmailNotifier : INotifier { public void Send(string message) { } }
public class SmsNotifier : INotifier { public void Send(string message) { } }
public abstract class NotifierFactory
{
public abstract INotifier Create();
}
public class EmailNotifierFactory : NotifierFactory
{
public override INotifier Create() => new EmailNotifier();
}
public class SmsNotifierFactory : NotifierFactory
{
public override INotifier Create() => new SmsNotifier();
}
// Calling code depends on NotifierFactory, never on EmailNotifier or SmsNotifier directly.
void Notify(NotifierFactory factory, string message) => factory.Create().Send(message);
Abstract Factory takes this further: it produces a whole family of related objects through one interface, guaranteeing the objects it returns are all compatible with each other. The classic example is a UI toolkit that must never mix a "light theme" button with a "dark theme" checkbox:
public interface IButton { void Render(); }
public interface ICheckbox { void Render(); }
public interface IWidgetFactory
{
IButton CreateButton();
ICheckbox CreateCheckbox();
}
public class DarkThemeFactory : IWidgetFactory
{
public IButton CreateButton() => new DarkButton();
public ICheckbox CreateCheckbox() => new DarkCheckbox();
}
public class LightThemeFactory : IWidgetFactory
{
public IButton CreateButton() => new LightButton();
public ICheckbox CreateCheckbox() => new LightCheckbox();
}
// Given one factory, every widget it produces is guaranteed to match the same theme.
void BuildToolbar(IWidgetFactory factory)
{
var button = factory.CreateButton();
var checkbox = factory.CreateCheckbox();
}
The distinction that matters in an interview: Factory Method produces one kind of object through inheritance (subclass overrides which type gets built); Abstract Factory produces a family of related objects through composition (an object holding several creation methods that must stay in sync with each other).