Video in progress

Strong Junior 🧭 Design patterns

What is the difference between Factory Method and Abstract Factory?

Factory Method creates one product, and a method (often in a subclass) decides which class it is. Abstract Factory gives an interface that creates a whole family of products that fit together.

📖 Answer

Factory Method: "give me one Parser":

abstract class ImportJob {
    protected abstract Parser createParser();
    void run(InputStream in) { createParser().parse(in).forEach(this::save); }
}
class CsvImportJob extends ImportJob {
    protected Parser createParser() { return new CsvParser(); }
}

Abstract Factory: "give me a set that works together". For example, two different cloud providers:

interface CloudFactory {
    FileStorage storage();
    MessageQueue queue();
    SecretStore secrets();
}

class AwsFactory implements CloudFactory { /* S3, SQS, SecretsManager */ }
class LocalFactory implements CloudFactory { /* disk, in-memory queue, .env */ }

What matters here is that the products don't get mixed up. A storage from AwsFactory and a queue from LocalFactory may not work together; Abstract Factory guarantees that with a single choice.

In short: Factory Method is a single method, Abstract Factory is an object that is a set of methods. Often a Factory Method lives inside each method of an Abstract Factory.