Factory Method & Abstract Factory

Decoupling object creation from use — simple factories, the Factory Method pattern, Abstract Factory for families of related objects, registries, and how they look in Java, Python and TypeScript.

Intermediate 2 min readLesson 5 of 24 Interview Q&A

Calling new ConcreteClass() everywhere couples your code to concrete types. Factories put creation in one place, so the rest of the code works with interfaces and new types can be added without touching callers.

There are three related ideas, from simplest to most structured.

1. Simple factory (not a GoF pattern, but the most common)

A function or static method that decides which class to instantiate.

interface Notifier { void send(String to, String msg); }
class EmailNotifier implements Notifier { public void send(String to, String msg) {...} }
class SmsNotifier   implements Notifier { public void send(String to, String msg) {...} }
class PushNotifier  implements Notifier { public void send(String to, String msg) {...} }

final class Notifiers {
    static Notifier of(String channel) {
        return switch (channel) {
            case "email" -> new EmailNotifier();
            case "sms"   -> new SmsNotifier();
            case "push"  -> new PushNotifier();
            default -> throw new IllegalArgumentException("unknown channel: " + channel);
        };
    }
}

Notifier n = Notifiers.of(user.preferredChannel());
n.send(user.address(), "Your order shipped");

The registry variant is open/closed: new types register themselves instead of editing a switch.

2. Factory Method

Intent: define an interface for creating an object, but let subclasses decide which class to instantiate. The base class contains the workflow; one step — "create the product" — is an overridable method.

createsDialog (abstract)render() · createButton()WindowsDialogcreateButton() → WinButtonWebDialogcreateButton() → HtmlButton«interface» Button
abstract class Dialog {
    void render() {                       // shared workflow
        Button ok = createButton();       // the factory method
        ok.onClick(this::close);
        ok.render();
    }
    protected abstract Button createButton();
    void close() {}
}

class WindowsDialog extends Dialog {
    protected Button createButton() { return new WindowsButton(); }
}
class WebDialog extends Dialog {
    protected Button createButton() { return new HtmlButton(); }
}

Dialog d = isWeb ? new WebDialog() : new WindowsDialog();
d.render();

Real examples: Iterable.iterator() (each collection creates its own iterator), Collection.stream(), JDBC's Connection.createStatement(), Django's get_queryset().

3. Abstract Factory

Intent: create families of related objects without specifying their concrete classes. It guarantees the products are compatible with each other.

Example: a UI toolkit with light and dark themes, or cloud-agnostic code with AWS and GCP implementations. You never want an AWS queue mixed with a GCP blob store by accident.

StorageQueueSecretsAWSGCPDevS3StorageSqsQueueAwsSecretsGcsStoragePubSubQueueGcpSecretsLocalStorageInMemoryQueueEnvSecrets
Each row is one concrete factory producing a compatible family.
interface CloudFactory {
    BlobStorage storage();
    MessageQueue queue();
    SecretStore secrets();
}

class AwsFactory implements CloudFactory {
    public BlobStorage storage() { return new S3Storage(); }
    public MessageQueue queue()  { return new SqsQueue(); }
    public SecretStore secrets() { return new AwsSecrets(); }
}
class LocalFactory implements CloudFactory {
    public BlobStorage storage() { return new LocalStorage(Path.of("/tmp/blobs")); }
    public MessageQueue queue()  { return new InMemoryQueue(); }
    public SecretStore secrets() { return new EnvSecrets(); }
}

// Chosen once, at startup
CloudFactory cloud = "prod".equals(env) ? new AwsFactory() : new LocalFactory();
UploadService uploads = new UploadService(cloud.storage(), cloud.queue());

Comparing them

Simple factoryFactory MethodAbstract Factory
CreatesOne product, chosen by a parameterOne product, chosen by subclassA family of related products
MechanismFunction / switch / registryInheritance (override a method)Composition (pass a factory object)
Adding a typeEdit switch or registerAdd a subclassAdd a factory class (adding a new product kind changes every factory)
Key takeaways
  • Factories move new into one place so clients depend on interfaces.
  • Simple factory/registry: choose a class by key — the everyday version.
  • Factory Method: a base-class workflow with an overridable creation step.
  • Abstract Factory: create compatible families of objects; swap the whole family at once.
  • In practice, a function returning an instance is often enough.
Interview questions
QFactory Method vs Abstract Factory?medium

Factory Method uses inheritance: a class defers creation of one product to subclasses via an overridable method. Abstract Factory uses composition: an object with several creation methods produces a family of related products, and clients receive the factory as a dependency. Abstract Factory is often implemented with factory methods.