All topics
library
intermediate

Factory Method & Abstract Factory

Use factory patterns to decouple object creation from usage, and recognize them in JDK APIs.

Factory patterns encapsulate object creation, letting callers request objects without knowing the concrete class.

Factory = ordering food from a menu. You ask for 'pasta' (factory method) without knowing which chef makes it or how. The kitchen (factory) decides the recipe (implementation). You get the dish (product) without entering the kitchen.

Key Concepts

1
Factory Method: a method that returns an instance. The caller doesn't call new directly. JDK examples: List.of(), Optional.of(), LocalDate.of(), Integer.valueOf(), Collections.unmodifiableList().
2
Advantages over constructors: - Named: valueOf, of, from, create — more readable than new - Can return subtype (interface/abstract return type) - Can cache instances (Integer.valueOf caches -128 to 127) - Can return existing instance (flyweight/pool) - Can return different implementations based on input
3
Abstract Factory: a factory interface with multiple creation methods. Example: DataSourceFactory with createConnection(), createStatement(). Each database vendor provides an implementation. JDK example: DocumentBuilderFactory, TransformerFactory.
4
Static factory methods (Effective Java Item 1): prefer static factory methods over constructors. Common naming: of(), valueOf(), getInstance(), newInstance(), from(), create().
5
Spring uses factories extensively: BeanFactory, FactoryBean<T>, @Bean methods in @Configuration classes are all factory methods.