What does the factory pattern do for you in Java, and when is it better than calling a constructor directly?
A factory centralises the decision about which concrete type to create. The caller asks for something by name or by criteria, and the factory returns the object. The caller ends up holding the interface, so it never names the concrete class, and the knowledge of the available implementations lives in exactly one place.
public class Main {
public static void main(String[] args) {
Notification n = NotificationFactory.create("email");
System.out.println(n.send("hello"));
Notification m = NotificationFactory.create("sms");
System.out.println(m.send("hello"));
}
}
interface Notification {
String send(String message);
}
class EmailNotification implements Notification {
public String send(String message) { return "email sent: " + message; }
}
class SmsNotification implements Notification {
public String send(String message) { return "sms sent: " + message; }
}
class NotificationFactory {
static Notification create(String channel) {
if ("email".equals(channel)) { return new EmailNotification(); }
if ("sms".equals(channel)) { return new SmsNotification(); }
throw new IllegalArgumentException("unknown channel: " + channel);
}
}The output shows the separation working. The main method asks for an email notification and gets one, then asks for a text message and gets the other, and it never mentions either implementation class. The only place that knows both exist is the factory.
That matters most when creation is not trivial. If building a notification involved reading configuration, choosing a transport, retrying a connection or applying a template, that code would otherwise be scattered across every caller, and each copy would drift. Centralising it means the rules live in one file.
The other benefit is that the factory can return different types based on data. A method that takes a configuration and picks the implementation removes a chain of conditions from the caller. The trade-off is real, though: an extra layer to read, and a factory whose body is a long chain of conditionals has simply moved the problem rather than solved it.
The rule to state in an interview is that the factory earns its place when creation involves a decision. If the constructor call is obvious and nothing varies, use the constructor directly.