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.
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.
- 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.
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.
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.
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.
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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