LOW-LEVEL DESIGN · CREATIONAL PATTERNS · CREATIONAL · 23 OF 48

Factory Method Pattern in Java: Let Subclasses Pick the Class

The Factory Method pattern with a login code sender: a shared algorithm in an abstract creator, one overridable method that decides which delivery channel to create, adding a new channel without editing old code, and how it differs from a simple static factory, constructors and abstract factory.

Reported atOracle
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 134 lines, with a small main() demo. Save it as OtpFactoryMethodDemo.java, then run javac OtpFactoryMethodDemo.java && java OtpFactoryMethodDemo.

import java.util.Random;

/** Factory method with a login code sender: the base class runs the steps, subclasses pick the channel. */
public class OtpFactoryMethodDemo {

    // ---------- the product ----------
    interface DeliveryChannel {
        String name();

        void deliver(String to, String text);
    }

    static final class SmsChannel implements DeliveryChannel {
        @Override public String name() { return "sms"; }

        @Override
        public void deliver(String to, String text) {
            System.out.println("  [sms to " + to + "] " + text);
        }
    }

    static final class EmailChannel implements DeliveryChannel {
        @Override public String name() { return "email"; }

        @Override
        public void deliver(String to, String text) {
            System.out.println("  [email to " + to + "@example.com] " + text);
        }
    }

    // ---------- the problem: the algorithm and the choice of class are tangled ----------
    static final class TangledOtpService {
        void sendOtp(String kind, String user) {
            String code = "482913";
            if (kind.equals("sms")) {
                new SmsChannel().deliver(user, "Code " + code);
            } else if (kind.equals("email")) {
                new EmailChannel().deliver(user, "Code " + code);
            } else {
                throw new IllegalArgumentException("unknown kind: " + kind);   // push? edit this again
            }
        }
    }

    // ---------- the clean version: the creator ----------
    abstract static class OtpSender {
        private final Random random = new Random(7);   // fixed seed so the demo output is stable

        /** The shared steps. Final, so subclasses cannot change them. */
        final String sendCode(String user) {
            String code = String.valueOf(100_000 + random.nextInt(900_000));
            DeliveryChannel channel = createChannel();          // the factory method call
            channel.deliver(user, "Your login code is " + code + ". It expires in 5 minutes.");
            return code;
        }

        /** The factory method: each subclass decides which concrete channel to create. */
        protected abstract DeliveryChannel createChannel();
    }

    static final class SmsOtpSender extends OtpSender {
        @Override
        protected DeliveryChannel createChannel() {
            return new SmsChannel();
        }
    }

    static final class EmailOtpSender extends OtpSender {
        @Override
        protected DeliveryChannel createChannel() {
            return new EmailChannel();
        }
    }

    // ---------- added later: two new classes, no edits above ----------
    static final class PushChannel implements DeliveryChannel {
        @Override public String name() { return "push"; }

        @Override
        public void deliver(String to, String text) {
            System.out.println("  [push to " + to + "'s phone] " + text);
        }
    }

    static final class PushOtpSender extends OtpSender {
        @Override
        protected DeliveryChannel createChannel() {
            return new PushChannel();
        }
    }

    // ---------- the client only knows OtpSender ----------
    static final class LoginFlow {
        private final OtpSender sender;

        LoginFlow(OtpSender sender) {
            this.sender = sender;
        }

        void signIn(String user) {
            String code = sender.sendCode(user);
            System.out.println("  login flow stored code " + code + " for " + user);
        }
    }

    // ---------- for comparison: a simple static factory (not the classic pattern) ----------
    static final class ChannelFactory {
        private ChannelFactory() { }

        static DeliveryChannel forName(String name) {
            return switch (name) {
                case "sms" -> new SmsChannel();
                case "email" -> new EmailChannel();
                case "push" -> new PushChannel();
                default -> throw new IllegalArgumentException("unknown channel: " + name);
            };
        }
    }

    public static void main(String[] args) {
        System.out.println("Tangled version:");
        new TangledOtpService().sendOtp("sms", "user-17");

        System.out.println("Factory method, one subclass per channel:");
        new LoginFlow(new SmsOtpSender()).signIn("user-17");
        new LoginFlow(new EmailOtpSender()).signIn("user-23");
        new LoginFlow(new PushOtpSender()).signIn("user-31");

        System.out.println("Simple static factory, choice from a config string:");
        String configured = "email";
        DeliveryChannel channel = ChannelFactory.forName(configured);
        channel.deliver("support-team", "Daily report via " + channel.name());
    }
}

Notes

The problem

Here is the naive version. One method makes a random code, then checks a string. If it is SMS, create an SMS channel. If it is email, create an email channel. The steps around it, making the code and writing the message, are the same every time. Only the class being created changes. Yet adding push means opening this tested method and adding another branch, and every caller must pass the right magic string.

TangledOtpService
String code = randomCode();
if (kind.equals("sms")) {
    new SmsChannel().deliver(user, ..);
} else if (kind.equals("email")) {
    new EmailChannel().deliver(user, ..);
} else {
    throw new IllegalArgumentException();
}
// add push: edit this method again

The idea

The idea in plain words. A base class runs a fixed set of steps, and one of those steps needs an object. Instead of calling new itself, the base class calls its own method, create channel. Each subclass overrides that one method and returns the concrete class it wants. So the base class owns the algorithm, and the subclasses own the decision of which class to create. That one method is the factory method.

Factory method
  • a base class runs the steps
  • and needs an object for one
  • of them
  • it asks its own method:
  • createChannel()
  • each subclass overrides that
  • method and returns the
  • concrete class it wants

The participants

Four roles. The product is the delivery channel interface. Concrete products are SMS channel and email channel. The creator is the abstract OTP sender class, which holds the shared algorithm and declares the factory method. Concrete creators are SMS OTP sender and email OTP sender, and each one creates its matching channel. The creator only ever talks to the delivery channel interface, never to a concrete channel.

Code: the product

Start with the product. The delivery channel interface has two methods: a name, and deliver, which takes a recipient and the text. SMS channel implements it by calling an SMS gateway. Email channel implements it by sending mail. In the demo they just print. The important point is that the rest of the code depends only on this interface.

DeliveryChannel
interface DeliveryChannel {
    String name();
    void deliver(String to, String text);
}

final class SmsChannel
        implements DeliveryChannel {
    public void deliver(String to,
            String text) { /* gateway */ }
}

Code: the creator

Now the creator. OTP sender has a send code method marked final, so subclasses cannot change the steps. It makes a six digit code, calls create channel, delivers the message and returns the code. Create channel is protected and abstract. The base class knows that some channel will come back, but not which one. That gap is filled by the subclasses.

OtpSender
abstract static class OtpSender {
  final String sendCode(String user) {
    String code = newCode();
    DeliveryChannel ch = createChannel();
    ch.deliver(user, "Code " + code);
    return code;
  }
  protected abstract DeliveryChannel
      createChannel();
}

Code: concrete creators

The concrete creators are tiny. SMS OTP sender overrides create channel and returns a new SMS channel. Email OTP sender returns a new email channel. That is all. The code generation, the message text and the return value are written once, in the base class. A creator can also do setup inside its factory method, like passing a gateway key into the channel, without the base class ever knowing.

Concrete creators
final class SmsOtpSender
        extends OtpSender {
    @Override
    protected DeliveryChannel
            createChannel() {
        return new SmsChannel();
    }
}
// EmailOtpSender returns
// new EmailChannel()

Run-through

Follow one login. The login flow holds an OTP sender and does not know which kind. At startup it was given an SMS OTP sender. The user signs in, so the flow calls send code. The inherited method makes the code, then calls create channel. Because the object is an SMS OTP sender, the override runs and returns an SMS channel. The message goes out by SMS, and the code comes back for checking.

Adding a channel

Now push notifications arrive. You add a push channel class and a push OTP sender whose factory method returns it. You do not open OTP sender, you do not touch the SMS or email classes, and the login flow does not change. This is the open closed principle in action: the code is open for new kinds of channel and closed for editing. Tested code stays tested.

Adding push
  • new PushChannel
  • implements DeliveryChannel
  • new PushOtpSender
  • overrides createChannel()
  • OtpSender: unchanged
  • SmsOtpSender: unchanged
  • LoginFlow: unchanged
  • open for extension,
  • closed for modification

Simple static factory

Many teams call this a factory too. Channel factory has one static method, for name, with a switch that returns the right channel. It hides the new keyword and keeps creation in one place, which is often all you need, for example when the channel name comes from a config file. But it is not the factory method pattern. There is no subclass and no inheritance. Adding a channel still means editing the switch.

ChannelFactory
static DeliveryChannel forName(String n) {
  return switch (n) {
    case "sms" -> new SmsChannel();
    case "email" -> new EmailChannel();
    case "push" -> new PushChannel();
    default -> throw new
      IllegalArgumentException(n);
  };
}

Compare the two

So how do you choose? Use a simple static factory when the choice comes from data, like a name in a config file, and the list of types changes rarely. Use the factory method when a base class has real shared steps around the creation, and different subclasses need different products. In modern Java you can also pass a supplier of delivery channel into the constructor instead of subclassing. Same idea, less inheritance.

Static factory vs method
  • simple static factory
  • • one method, a switch
  • • choice from data (a string)
  • • new type: edit the switch
  • factory method
  • • overridable, in a creator
  • • choice from the subclass
  • • new type: add a subclass
  • • shared steps around it

When not to use it

The trade offs. You gain shared code that never names a concrete class, easy extension and easy testing, because a test subclass can return a fake channel. The cost is a parallel hierarchy: one creator subclass for every product. If you have only one channel and no sign of a second, a plain constructor call is simpler. Add the pattern when the second type actually appears.

Trade-offs
  • benefits
  • • no new of concrete classes
  • in the shared code
  • • new type = new class
  • • easy to test with a fake
  • costs
  • • a parallel class hierarchy
  • • one subclass per product
  • • overkill for one type

In Java

You use factory methods every day. Iterable declares the iterator method, and each collection, like array list or hash set, overrides it to return its own iterator class. Your for each loop never knows which one it got. Static factory methods are even more common: integer value of, which can return a cached object, list of, and optional of. They are useful, but they are the simple kind, not the subclass based pattern.

Where you see it
  • Iterable.iterator()
  • each collection returns its
  • own Iterator class
  • static factories (no subclass):
  • Integer.valueOf(42)
  • List.of("a", "b")
  • Optional.of(x)
  • NumberFormat.getInstance()

Neighbours

Its neighbours. Factory method creates one kind of product through an overridable method. Abstract factory is an object with several create methods that together produce a family of products that must match, which is the next episode. Builder assembles one complex object step by step. And notice that send code is itself a template method. A factory method is often just the creation step inside a template method.

How it differs
  • factory method: one method,
  • one product, via subclass
  • abstract factory: an object
  • with several create methods
  • for a family that must match
  • builder: one complex object,
  • step by step
  • template method: factory
  • method is its creation step

In LLD interviews

In interviews this comes up whenever you create objects by type: senders in a notification service, spots for different vehicles in a parking lot, payment processors, or file parsers. Say clearly whether you are using a simple factory or the factory method, and why. Common mistakes: calling a big switch statement the factory method pattern, and building a factory hierarchy for a class that has only one implementation.

Where it comes up
  • notification service:
  • email, SMS, push senders
  • parking lot: spot per vehicle
  • payment: card, UPI, wallet
  • file parsers: CSV, JSON
  • common mistakes:
  • • a giant switch called
  • "factory method"
  • • a factory for one class

Interview questions

What is the factory method pattern?

A base class defines an algorithm that needs an object, and instead of calling new it calls an overridable method to get it. Subclasses override that method to return the concrete class they want, so the base class depends only on the product interface.

What is the difference between a simple factory and the factory method pattern?

A simple factory is usually one static method with a switch that picks a class from a parameter; adding a type means editing it. The factory method pattern uses inheritance: each subclass overrides a creation method, so adding a type means adding a subclass, and shared steps live in the base class.

How does factory method support the open closed principle?

The creator code never names a concrete product, so a new product needs only a new product class and a new creator subclass. Existing, tested classes are not edited, which is the meaning of open for extension and closed for modification.

Can you give a factory method example from the Java standard library?

Iterable.iterator() is a good one: each collection overrides it to return its own Iterator implementation, and the enhanced for loop works only with the interface. Static methods such as Integer.valueOf and List.of are static factory methods, a related but simpler idea.

How is factory method different from abstract factory?

Factory method is a single overridable method that creates one product, usually inside a class with other logic. Abstract factory is an object whose whole job is creating a family of related products through several methods, so that all of them match each other.

What are the downsides of the factory method pattern?

It adds a creator subclass for every product, giving two parallel class hierarchies, and uses inheritance where composition might be simpler. For one or two stable types, a constructor call or a static factory is often clearer.

Can you implement factory method without inheritance in Java?

Yes. Pass a Supplier of the product into the class constructor and call get() where you would call the factory method. It keeps the same separation between the algorithm and the choice of class, with less inheritance.

Where would you use factory method in a notification system design?

A base sender class handles shared steps such as templating, retry and audit logging, and calls a createChannel method. SMS, email and push subclasses return their own channel, so adding WhatsApp later means adding classes, not editing the sender.