Abstract factory
An abstract factory is an interface that creates a whole family of related objects, with one implementation of that interface per family. It exists to stop you accidentally mixing pieces from two different families.
Detailed Explanation
Start with the problem, because this pattern is meaningless without it. You are writing an archiving service. It needs two collaborators: somewhere to put file bytes, and somewhere to record an index entry about them. Locally that means the filesystem and a SQLite file. In production it means object storage and a cloud table. Those pairs must match. A local blob store with a cloud index is a bug that only shows up when someone tries to download a file that is not there.
A plain factory creates one kind of thing. An abstract factory creates several kinds that belong together, and guarantees they come from the same set. The interface has one method per product: blobs(), metadata(). Each implementation returns its own vendor's versions of both. Your business logic takes the factory interface as a parameter and can no longer mix families, because it never names a concrete class at all.
The JDK's clearest example is JDBC. A java.sql.Connection is an abstract factory. Call createStatement(), prepareStatement(...), or createBlob() and you get PostgreSQL objects from a PostgreSQL connection and Oracle objects from an Oracle connection, never a mixture. java.nio.file.FileSystem is another: it manufactures Path, WatchService, and FileStore instances that all belong to the same filesystem provider, so a zip filesystem hands back zip-aware paths. AWT's Toolkit did the same job for platform-specific widget peers.
How it behaves in practice: the choice of family happens once, at startup, in the one place that reads configuration. Everything downstream receives the factory and stays ignorant. That single decision point is the real payoff, and it is why abstract factories and dependency injection containers show up together so often. A Spring @Configuration class selecting between two sets of beans by profile is doing this job with annotations instead of an interface.
Reach for it when two conditions both hold: you have more than one product type, and the products must be consistent with each other. If either is false, you want something smaller. One product type means a plain factory. Products that can be mixed freely mean separate factories, or no factory at all.
The costs are heavier than most patterns. You pay in classes: with two families and three product types you have three product interfaces, six implementations, one factory interface, and two factory implementations. Twelve types for something a constructor call used to do. Navigation suffers, because "where is this created" now needs two hops.
There is also a structural weakness worth knowing for interviews. Adding a new family is cheap: write one more factory implementation. Adding a new product type is expensive: every existing factory implementation stops compiling until you implement the new method. Abstract factories are open to new families and closed to new products. If your product list is still moving, this pattern will fight you, and a configuration object holding suppliers is the lighter answer.
Code Examples
public class StorageProviders {
// --- the product family: two types that must come from the same vendor ---
interface BlobStore {
void put(String key, byte[] data);
}
interface MetadataStore {
void record(String key, long size);
}
// --- the abstract factory: one method per product type ---
interface StorageProvider {
BlobStore blobs();
MetadataStore metadata();
}
// --- family 1: local disk ---
record LocalBlobStore(String root) implements BlobStore {
public void put(String key, byte[] data) {
System.out.println("wrote " + data.length + " bytes to " + root + "/" + key);
}
}
record LocalMetadataStore(String root) implements MetadataStore {
public void record(String key, long size) {
System.out.println("indexed " + key + " in " + root + "/index.db");
}
}
record LocalStorage(String root) implements StorageProvider {
// Both products are built from the same root, so they cannot disagree.
public BlobStore blobs() {
return new LocalBlobStore(root);
}
public MetadataStore metadata() {
return new LocalMetadataStore(root);
}
}
// --- family 2: cloud ---
record CloudBlobStore(String bucket) implements BlobStore {
public void put(String key, byte[] data) {
System.out.println("PUT s3://" + bucket + "/" + key + " (" + data.length + " bytes)");
}
}
record CloudMetadataStore(String table) implements MetadataStore {
public void record(String key, long size) {
System.out.println("INSERT INTO " + table + " (key, size) VALUES (?, ?)");
}
}
record CloudStorage(String bucket, String table) implements StorageProvider {
public BlobStore blobs() {
return new CloudBlobStore(bucket);
}
public MetadataStore metadata() {
return new CloudMetadataStore(table);
}
}
// Business logic names only the factory interface. It cannot mix families.
static void archive(StorageProvider provider, String key, byte[] data) {
provider.blobs().put(key, data);
provider.metadata().record(key, data.length);
}
public static void main(String[] args) {
// The family is chosen once, here, and nowhere else in the program.
StorageProvider provider = "prod".equals(System.getenv("ENV"))
? new CloudStorage("acme-archive", "blob_index")
: new LocalStorage("/tmp/archive");
archive(provider, "invoice-8812.pdf", new byte[2048]);
// prints (default env): wrote 2048 bytes to /tmp/archive/invoice-8812.pdf
// indexed invoice-8812.pdf in /tmp/archive/index.db
}
}Common Gotchas
Adding a product type breaks every factory
put a third method on `StorageProvider` and both `LocalStorage` and `CloudStorage` fail to compile until they implement it. A `default` method can soften the blow, but only if a sensible default exists.
One factory per environment is not the same as one factory per class
the pattern pays off when several products must agree. Writing an abstract factory around a single product type buys nothing and adds two files.
The factory interface can be a lambda when it has one method
with two or more creation methods it cannot, because a functional interface needs exactly one abstract method. That constraint is often what tells you whether you have a factory or an abstract factory.
Do not let concrete types leak into signatures
if `archive` took a `CloudBlobStore`, the compiler would tie your business logic to one vendor again and the whole structure would be decoration.