Factory Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Factory Pattern runs in O(1) time and O(1) space, in Java as in every other language.
- ✓Static factory methods are the canonical form and the standard library is full of them: List.of, Optional.of, Integer.valueOf, EnumSet.noneOf.
- ✓Prefer a static factory to a public constructor, which is Effective Java Item 1, for three reasons that matter in review: the method has a name so two factories with the same parameter types can coexist, it is not required to create a new object so it can cache or return a shared instance, and it can return a subtype.
- ✓The Java trap: Reflective factories built on Class.forName plus newInstance are the ones that break in production rather than in the IDE.
- ✓A static factory that returns a cached instance turns allocation into a field read, which is why Integer.valueOf beats new Integer for small values and why the latter is now removed.
What Factory Pattern actually is
Factory Pattern in Java: what you actually reach for
Java implementation
public sealed interface Shape permits Circle, Square {
// Static factory: has a NAME, may cache, may return a subtype.
static Shape of(String kind, double n) {
return switch (kind) {
case "circle" -> new Circle(n);
case "square" -> new Square(n);
default -> throw new IllegalArgumentException("unknown: " + kind);
};
}
}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
class Areas {
// Java 21: the compiler PROVES this covers the sealed family. No default.
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.side() * q.side();
};
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Factory Pattern?
Static factory methods are the canonical form and the standard library is full of them: List.of, Optional.of, Integer.valueOf, EnumSet.noneOf. java.util.ServiceLoader discovers implementations declared in META-INF/services or in a module-info provides clause, which is the JDK answer to an open product set. Since Java 17, a sealed interface plus records gives a closed family the compiler knows about, and since Java 21 pattern matching for switch checks that family exhaustively.
What is the most common Java mistake when implementing Factory Pattern?
Reflective factories built on Class.forName plus newInstance are the ones that break in production rather than in the IDE. Under the module system an unexported package is not reflectively accessible without an opens directive, and under a native-image or aggressive shrinker the class is not in the binary at all because nothing references it statically. The failure is a ClassNotFoundException or InaccessibleObjectException at first use, on the deployed artifact only. ServiceLoader is the supported alternative precisely because build tooling can see the declaration.
How does Factory Pattern actually perform in Java?
A static factory that returns a cached instance turns allocation into a field read, which is why Integer.valueOf beats new Integer for small values and why the latter is now removed. Escape analysis can eliminate short-lived factory products entirely when the factory inlines, so keeping the factory body small enough to inline is worth more than any micro-optimisation inside it. Reflective construction is roughly an order of magnitude slower than a direct new on the first calls and stays slower even after JIT warm-up unless a MethodHandle is bound once and reused. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.