Factory Methods
1. What Is a Factory? (beginner)
Factory method = static method that makes objects for you (instead of new). Hides complexity: Integer.valueOf(5) instead of new Integer(5). Like shop: ask, get ready product!
2. Code — Why Better Than new?
// Plain new (always fresh object!):
Integer a = new Integer(100); // deprecated! (always new!)
// Factory (smart: cache + clean!):
Integer b = Integer.valueOf(100); // may REUSE cached -128..127!
Integer c = Integer.valueOf(100); // same cached (== true for small!)
LocalDate d = LocalDate.of(2026, 9, 22); // named clearly (of = parts!)
List<String> list = List.of("a", "b"); // ready list (no new ArrayList+add!)
Benefits: named (of, from), cached (saves memory), controlled (can return subtype/null!), no new clutter.
3. Write Your Own Factory (exam pattern!)
class User {
private String name; // private ctor (force factory!)
private User(String n) { name = n; }
public static User of(String n) { // factory!
if (n == null) return null; // control!
return new User(n.trim()); // clean + build!
}
}
User u = User.of(" Asha "); // trimmed! (new hidden!)
4. Traps
- Constructor always fresh; factory MAY reuse (cache!). Don't
==wrappers! - Private ctor + factory = controlled creation (singleton pattern uses this!).
5. Exam Points
- Define +
valueOf/ofexamples — 5 marks, frequent. - Factory vs
new(cache/naming) — 3 marks, frequent.