Factory Method and Abstract Factory

Junior Always asked 7 min

On this page

The question

What is the difference between Factory Method and Abstract Factory?

30-second answer

Factory Method is one method that subclasses override to choose one product, so it works through inheritance. Abstract Factory is an object with several create methods that produce a family of related products, so it works through composition: the client is handed a factory. Use Abstract Factory when the products must match each other.

Understand it

The client asks, the factory picks

Step by step

The client asks the factory for an "sms" channel. It never names a concrete class.

Step 1 of 5
View as text

A client box on the left, a factory box in the middle, and product classes on the right: Email, SMS and, later, Push. A code line at the top shows the current call.

The client asks the factory for an "sms" channel. It never names a concrete class. A request travels from the client toward the factory.

The factory looks up "sms" and picks the matching product. This choice lives in one place. An arrow joins the factory to the SMS class.

Only the factory says new SmsNotification(). The client does not depend on that class. The SMS class is highlighted.

The factory returns it as the Notification interface, so the client only calls send(). The object travels back to the client, labelled Notification.

A new Push channel changes the factory and adds one class. The client code does not change. A Push class appears on the right, and a mark says the client needs no edits.

A client box on the left, a factory box in the middle, and product classes on the right: Email, SMS and, later, Push. A code line at the top shows the current call.

The client asks the factory for an "sms" channel. It never names a concrete class. A request travels from the client toward the factory.

The factory looks up "sms" and picks the matching product. This choice lives in one place. An arrow joins the factory to the SMS class.

Only the factory says new SmsNotification(). The client does not depend on that class. The SMS class is highlighted.

The factory returns it as the Notification interface, so the client only calls send(). The object travels back to the client, labelled Notification.

A new Push channel changes the factory and adds one class. The client code does not change. A Push class appears on the right, and a mark says the client needs no edits.

Takeaway: A factory moves new and the choice of class into one place, so clients depend on an interface and new products leave their code untouched.

Factory Method vs Abstract Factory

Compare

Factory Method: one method that subclasses override. Each subclass creates one product, and the base class uses it without knowing which.

View as text

Three levels on one layout: a creator type at the top, two concrete creators below it, and the products each one makes at the bottom.

Factory Method: one method that subclasses override. Each subclass creates one product, and the base class uses it without knowing which. The top box is abstract class Alerts with createNotification(). EmailAlerts makes Email and SmsAlerts makes SMS, one product each.

Abstract Factory: an object with several create methods. Each one creates a family of products that belong together, so an SMS sender never gets an HTML message. The top box is interface ChannelFactory with createMessage() and createSender(). EmailChannel makes an HTML message and an SMTP sender. SmsChannel makes a text message and an SMS sender.

Three levels on one layout: a creator type at the top, two concrete creators below it, and the products each one makes at the bottom.

Factory Method: one method that subclasses override. Each subclass creates one product, and the base class uses it without knowing which. The top box is abstract class Alerts with createNotification(). EmailAlerts makes Email and SmsAlerts makes SMS, one product each.

Abstract Factory: an object with several create methods. Each one creates a family of products that belong together, so an SMS sender never gets an HTML message. The top box is interface ChannelFactory with createMessage() and createSender(). EmailChannel makes an HTML message and an SMTP sender. SmsChannel makes a text message and an SMS sender.

Takeaway: Factory Method varies one product through a subclass; Abstract Factory varies a whole family of related products through an object you pass in.

Which factory fitsIf only one class exists, use new. If input at runtime decides the product, use a static factory. If a subclass decides, use Factory Method. If several products must match each other, use Abstract Factory.What decidesthe product?Only one class:just newInput at runtime:static factoryA subclass:Factory MethodProducts mustmatch:Abstract Factory
Which factory fitsIf only one class exists, use new. If input at runtime decides the product, use a static factory. If a subclass decides, use Factory Method. If several products must match each other, use Abstract Factory.What decidesthe product?Only one class:just newInput at runtime:static factoryA subclass:Factory MethodProducts mustmatch:Abstract Factory
Which factory fits

In code

interface Notification { String send(String text); }
class EmailNotification implements Notification { public String send(String t) { return "email: " + t; } }
class SmsNotification implements Notification { public String send(String t) { return "sms: " + t; } }

class NotificationFactory {
    private static final Map<String, Supplier<Notification>> CHANNELS = Map.of(
        "email", EmailNotification::new,
        "sms", SmsNotification::new);

    static Notification create(String channel) {
        Supplier<Notification> maker = CHANNELS.get(channel);
        if (maker == null) throw new IllegalArgumentException("Unknown channel: " + channel);
        return maker.get();
    }
}

NotificationFactory.create("sms").send("hi");   // "sms: hi"
A static factory: not a GoF (Gang of Four) pattern, but the one you meet most
// Factory Method: a subclass decides which product to create.
abstract class Alerts {
    abstract Notification createNotification();          // the factory method
    String alert(String text) { return createNotification().send(text); }
}
class SmsAlerts extends Alerts {
    @Override Notification createNotification() { return new SmsNotification(); }
}

// Abstract Factory: one object creates a family of products that belong together.
interface Message { String body(); }
interface Sender { String deliver(Message message); }
interface ChannelFactory {
    Message createMessage(String text);
    Sender createSender();
}
class EmailChannel implements ChannelFactory {
    public Message createMessage(String text) { return () -> "<p>" + text + "</p>"; }
    public Sender createSender() { return m -> "smtp: " + m.body(); }
}

ChannelFactory factory = new EmailChannel();
factory.createSender().deliver(factory.createMessage("hi"));   // "smtp: <p>hi</p>"
Factory Method and Abstract Factory
Factory Method with Alerts and SmsAlertsThe abstract class Alerts declares createNotification and uses it in alert. SmsAlerts extends Alerts and overrides createNotification to return an SmsNotification, which implements Notification.usescreates«abstract»Alerts+alert(text)+createNotification()«interface»Notification+send(text)SmsAlertsSmsNotification
Factory Method with Alerts and SmsAlertsThe abstract class Alerts declares createNotification and uses it in alert. SmsAlerts extends Alerts and overrides createNotification to return an SmsNotification, which implements Notification.usescreates«abstract»Alerts+alert(text)+createNotification()«interface»Notification+send(text)SmsAlertsSmsNotification
Factory Method: SmsAlerts overrides one method
private static final Map<String, Supplier<Notifier>> REGISTRY = Map.of(
    "email", EmailNotifier::new,
    "sms", SmsNotifier::new);

static Notifier create(String type) {
    Supplier<Notifier> constructor = REGISTRY.get(type);
    if (constructor == null) throw new IllegalArgumentException("unknown notifier: " + type);
    return constructor.get();
}
A factory backed by a map of constructors replaces the switch

Solve it

Support a second cloud provider without if (aws) everywhere

A service stores files in S3 (Simple Storage Service) and sends messages to SQS (Simple Queue Service), with AWS (Amazon Web Services) classes created all over the code. It must also run on Google Cloud, and mixing an AWS store with a Google queue must be impossible. Design the creation.

  1. Spot the family. Storage and queue come in matched sets: AWS with AWS, Google with Google. Matched products point to Abstract Factory.
  2. Define the products and the factory. FileStore and MessageQueue are interfaces. CloudFactory has fileStore() and messageQueue(), with one implementation per provider.
  3. Choose once. Read the provider from configuration at startup and build one factory. Nothing else mentions AWS or Google.
  4. Name the trade-off. A new provider is one new factory. A new product, such as a cache, means a new method on every factory.
  5. Check. Business code imports only the interfaces, and a test passes an in-memory factory.
interface FileStore { void put(String key, byte[] data); }
interface MessageQueue { void send(String message); }

interface CloudFactory {
    FileStore fileStore();
    MessageQueue messageQueue();
}

class AwsFactory implements CloudFactory {
    public FileStore fileStore() { return new S3FileStore(); }
    public MessageQueue messageQueue() { return new SqsQueue(); }
}
class GcpFactory implements CloudFactory {
    public FileStore fileStore() { return new GcsFileStore(); }
    public MessageQueue messageQueue() { return new PubSubQueue(); }
}

static CloudFactory forProvider(String provider) {
    return switch (provider) {
        case "aws" -> new AwsFactory();
        case "gcp" -> new GcpFactory();
        default -> throw new IllegalArgumentException("unknown provider: " + provider);
    };
}
One factory per provider; the provider is chosen once

How to answer

  • Factory Method: abstract Notification createNotification(), overridden by each subclass.
  • Abstract Factory: createMessage() and createSender() on one factory, so the pair always matches.
  • Both leave the client depending on interfaces, not on concrete classes.
  • A new product kind is cheap for Factory Method but changes every Abstract Factory.

Common mistakes

  • Calling any method that returns an object a Factory Method; the GoF pattern is about a subclass overriding it.
  • Describing Abstract Factory as just "a factory of factories".

Follow-up questions

Why use a factory instead of just calling new?

Calling new ties the caller to one concrete class and to how it is built. A factory moves that decision to one place, so callers depend on an interface and new products leave their code alone. It can also cache objects, pick a class from input and validate arguments, none of which a constructor can do. If only one class exists, new is fine.

  • A factory method has a name, so it can say what it creates.
  • It can return a subclass or a cached object, unlike a constructor.
  • One creation point keeps the choice of class out of many callers.

See it in the infographic: The client asks, the factory picks

What is a simple factory, and how is it different from Factory Method?

A simple factory is one class, usually with a static method, that picks a product from an argument, such as NotificationFactory.create("sms"). It is not a GoF pattern, but it is very common. Factory Method relies on subclasses overriding a method. Choose a simple factory when input decides the product, and Factory Method when the subclass does.

  • Simple factory: the choice is made inside one method, from input at runtime.
  • Factory Method: the choice is fixed by which subclass you instantiate.
  • A Map of Suppliers avoids a growing switch in a simple factory.

See it in the infographic: The client asks, the factory picks

How would you write a factory that does not need editing for each new product?

Keep the choices in a Map<String, Supplier<Notification>> and look up the channel instead of switching on it. A new product is then one more entry. Fail clearly on an unknown key with an IllegalArgumentException. In Spring, injecting a Map<String, Notification> builds that map for you from the beans, keyed by bean name.

  • The lookup stays the same as products are added.
  • An unknown key throws rather than returning null.
  • In Spring, a new @Component adds an entry with no factory edit.
private static final Map<String, Supplier<Notification>> CHANNELS = Map.of(
    "email", EmailNotification::new,
    "sms", SmsNotification::new);

static Notification create(String channel) {
    Supplier<Notification> maker = CHANNELS.get(channel);
    if (maker == null) throw new IllegalArgumentException("Unknown channel: " + channel);
    return maker.get();
}

See it in the infographic: The client asks, the factory picks

When is Abstract Factory the right choice?

When products must be used together and mixing them is a bug. For notifications, an email channel needs an HTML message and an SMTP (Simple Mail Transfer Protocol) sender, and an SMS channel needs a short text and an SMS gateway. With one ChannelFactory chosen at startup, the rest of the code cannot pair an HTML message with an SMS gateway.

  • The factory is chosen once, and the client uses only interfaces after that.
  • JDBC (Java Database Connectivity) works this way, because a Connection creates Statement objects that match its driver.
  • One new family means one new factory class.

See it in the infographic: Factory Method vs Abstract Factory

How do factories relate to the Open/Closed Principle?

Clients stay closed to change: they only know the interface, so a new product leaves them alone. Something still has to change, and that is the factory or the registration. A factory does not remove that edit; it concentrates it in one place. Factory Method goes further, since a new subclass extends the design without editing existing classes.

  • Client code stays closed; the composition point stays open.
  • A switch inside one factory is much better than a switch in every caller.
  • Dependency injection moves that composition point into configuration.

See it in the infographic: The client asks, the factory picks

Where does the JDK (Java Development Kit) use a static factory?

List.of(...), Optional.of(...), Integer.valueOf(...) and HttpClient.newHttpClient(). List.of(1) returns an internal ImmutableCollections.List12, a class callers never name, so the JDK can change it freely. Integer.valueOf can also return a cached object, which a constructor can never do.

How does Spring relate to these patterns?

BeanFactory is a factory in the general sense: you ask for a type and it picks and wires the object. A FactoryBean lets you plug in your own creation logic for one bean, and a @Bean method is a factory method. Most application code no longer needs its own factory, because injection does the choosing.

What is the cost of adding a new product kind to an Abstract Factory?

A new method on the interface forces a change in every implementation, because each family must now supply that product. Adding a whole new family is cheap, since it is just one new class. So the pattern fits when families grow more often than the kinds of product do.

Check yourself

1. A factory creates notifications from a channel name, and clients call only Notification.send(). What changes when you add a Push channel?
Show answers
  • One new class and the factory's table of channels: Correct. Only the factory names concrete classes, so the clients stay as they are.
  • Every class that sends a notification: Incorrect. Clients depend only on the interface, which does not change.
  • The Notification interface and all its implementations: Incorrect. Push implements the same send() method, so the interface stays as it is.
2. An HTML message must always go with an SMTP sender, and a short text with an SMS gateway. Which pattern keeps the pairs from being mixed?
Show answers
  • Abstract Factory: Correct. One factory object creates both products, so each family always matches.
  • Factory Method: Incorrect. It varies one product through a subclass and does not tie two products together.
  • Singleton: Incorrect. It limits how many instances exist and says nothing about which products match.
3. Which code is the GoF Factory Method?
Show answers
  • A subclass overrides createNotification(), and the base class calls it: Correct. The base class defers the choice of product to a subclass, which is the pattern.
  • A static create(String) method containing a switch: Incorrect. That is a useful simple factory, but no subclass overrides anything.
  • A public constructor that takes the channel name: Incorrect. A constructor always creates its own class, so it cannot choose a product.