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.
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");class EmailNotifier:
def send(self, to, msg): ...
class SmsNotifier:
def send(self, to, msg): ...
# A registry dict is the idiomatic Python factory
NOTIFIERS = {"email": EmailNotifier, "sms": SmsNotifier}
def make_notifier(channel: str):
try:
return NOTIFIERS[channel]()
except KeyError:
raise ValueError(f"unknown channel: {channel}") from None
# Plugins can register themselves without editing the factory
def register(name):
def deco(cls):
NOTIFIERS[name] = cls
return cls
return deco
@register("push")
class PushNotifier:
def send(self, to, msg): ...interface Notifier { send(to: string, msg: string): Promise<void>; }
const registry = new Map<string, () => Notifier>([
["email", () => new EmailNotifier()],
["sms", () => new SmsNotifier()],
]);
export function makeNotifier(channel: string): Notifier {
const create = registry.get(channel);
if (!create) throw new Error(`unknown channel: ${channel}`);
return create();
}
export const registerNotifier = (name: string, create: () => Notifier) =>
registry.set(name, create);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.
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();from abc import ABC, abstractmethod
class Dialog(ABC):
def render(self):
ok = self.create_button() # factory method
ok.on_click(self.close)
ok.render()
@abstractmethod
def create_button(self) -> "Button": ...
def close(self): ...
class WindowsDialog(Dialog):
def create_button(self): return WindowsButton()
class WebDialog(Dialog):
def create_button(self): return HtmlButton()abstract class Dialog {
render() {
const ok = this.createButton(); // factory method
ok.onClick(() => this.close());
ok.render();
}
protected abstract createButton(): Button;
close() {}
}
class WindowsDialog extends Dialog {
protected createButton() { return new WindowsButton(); }
}
class WebDialog extends Dialog {
protected createButton() { return new HtmlButton(); }
}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.
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());class CloudFactory(Protocol):
def storage(self) -> BlobStorage: ...
def queue(self) -> MessageQueue: ...
class AwsFactory:
def storage(self): return S3Storage()
def queue(self): return SqsQueue()
class LocalFactory:
def storage(self): return LocalStorage("/tmp/blobs")
def queue(self): return InMemoryQueue()
cloud = AwsFactory() if env == "prod" else LocalFactory()
uploads = UploadService(cloud.storage(), cloud.queue())interface CloudFactory {
storage(): BlobStorage;
queue(): MessageQueue;
}
const aws: CloudFactory = { storage: () => new S3Storage(), queue: () => new SqsQueue() };
const local: CloudFactory = {
storage: () => new LocalStorage("/tmp/blobs"),
queue: () => new InMemoryQueue(),
};
const cloud = env === "prod" ? aws : local;
const uploads = new UploadService(cloud.storage(), cloud.queue());Comparing them
| Simple factory | Factory Method | Abstract Factory | |
|---|---|---|---|
| Creates | One product, chosen by a parameter | One product, chosen by subclass | A family of related products |
| Mechanism | Function / switch / registry | Inheritance (override a method) | Composition (pass a factory object) |
| Adding a type | Edit switch or register | Add a subclass | Add a factory class (adding a new product kind changes every factory) |
- Factories move
newinto 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.
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.