Factory
A factory is code that creates objects on your behalf and returns them as an interface or base type, so the caller never names a concrete class. It replaces new at the call site with a method you control.
Detailed Explanation
new is a hard commitment. Writing new EmailNotifier(...) ties that line of code to one exact class. If you later need SMS notifications, or a no-op notifier in tests, you have to edit every call site. A factory removes that commitment: callers ask for a Notifier and something else decides which class to build.
Two different things share the name "factory", and interviewers like the distinction.
A static factory method is a named static method that returns an instance, used instead of a public constructor. The JDK is full of them: List.of(...), Integer.valueOf(7), Optional.of(x), DateTimeFormatter.ofPattern("yyyy-MM-dd"), Executors.newFixedThreadPool(4). They win over constructors for three reasons. They have names, so Temperature.ofCelsius and Temperature.ofFahrenheit can coexist even though both take a single double. They can return a cached instance instead of a new one, which is how Integer.valueOf reuses boxed values from -128 to 127. And they can return a subtype, which is how List.of() gives you a different, smaller implementation for zero elements than for twelve.
The factory method pattern is the GoF version: a method, usually overridable, that subclasses redefine to choose the product. Collection.iterator() is exactly this. ArrayList returns one kind of iterator, LinkedList returns another, and code that writes an enhanced for loop works with both without knowing which. Frameworks use it heavily: DocumentBuilderFactory, SSLSocketFactory, Spring's FactoryBean.
A common practical shape is a registry factory: a Map from a string key to a Supplier of the product. Configuration names a channel, the factory looks it up, and adding a channel means adding a map entry rather than editing a switch statement. That is the Open/Closed Principle in about eight lines.
When would a learner reach for one? Whenever the concrete type depends on data you only have at runtime, such as a config file, a database column, or an HTTP header. Also when construction is not trivial: validation, caching, pooling, or picking an implementation based on the platform.
The costs. Every factory adds a layer of indirection, so tracing "where does this object actually come from" takes one extra hop, and stack traces gain frames. A factory also hides the concrete type, which is the point, but it means your IDE's "go to definition" lands on an interface. And a static factory method cannot be overridden or mocked easily, so a class that calls SomeFactory.create() internally is harder to test than one that receives its collaborator.
The wrong call is a factory for a class with one implementation that will never have another. UserServiceFactory returning new UserServiceImpl() earns nothing and costs a file. If you only want to swap implementations for tests, plain constructor injection does that already.
Code Examples
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
public class NotifierFactory {
// The product type. Callers only ever hold this interface.
public interface Notifier {
void send(String message);
}
// Nested records are implicitly static, so they need no outer instance.
record EmailNotifier(String address) implements Notifier {
public void send(String message) {
System.out.println("email to " + address + ": " + message);
}
}
record SmsNotifier(String number) implements Notifier {
public void send(String message) {
System.out.println("sms to " + number + ": " + message);
}
}
// A registry of suppliers. Adding a channel means adding a map entry,
// not editing a switch statement in the middle of this class.
private static final Map<String, Supplier<Notifier>> CHANNELS = Map.of(
"email", () -> new EmailNotifier("ops@example.com"),
"sms", () -> new SmsNotifier("+441234567890"));
// Returning Optional forces the caller to handle an unknown channel name.
public static Optional<Notifier> forChannel(String channel) {
Supplier<Notifier> supplier = CHANNELS.get(channel);
return Optional.ofNullable(supplier).map(Supplier::get);
}
public static void main(String[] args) {
forChannel("sms").ifPresent(n -> n.send("build 412 failed"));
// prints: sms to +441234567890: build 412 failed
System.out.println(forChannel("carrier-pigeon").isPresent()); // prints: false
}
}Static factory methods solve a problem constructors cannot: naming.
// Static factory methods solve a problem constructors cannot: naming.
public final class Temperature {
private final double celsius;
// Private, so every instance comes through a named factory method.
private Temperature(double celsius) {
this.celsius = celsius;
}
// Two constructors both taking one double would clash. These do not.
public static Temperature ofCelsius(double degrees) {
return new Temperature(degrees);
}
public static Temperature ofFahrenheit(double degrees) {
return new Temperature((degrees - 32) * 5 / 9);
}
public double celsius() {
return celsius;
}
public static void main(String[] args) {
System.out.println(Temperature.ofFahrenheit(212).celsius()); // prints: 100.0
}
}Common Gotchas
Static factory methods are hard to substitute in tests
a class that calls `Foo.create()` inside a method has a hidden dependency you cannot replace without a mocking library that rewrites static calls. Take the collaborator as a constructor parameter instead.
A factory may return a cached object, so `==` can surprise you
`Integer.valueOf(100) == Integer.valueOf(100)` is true because of the small-integer cache, while the same expression with `1000` is false. Compare with `equals` unless identity is the thing you mean to test.
Returning the concrete type defeats the purpose
declare the return type as the interface. If `forChannel` returned `EmailNotifier`, callers would compile against the implementation and you would be back where you started.
A private constructor plus a factory lets you change your mind later
you can switch from returning a new object to returning a pooled or cached one without touching a single caller. A public constructor locks that door.