The Factory Method pattern defines a method for creating an object but lets subclasses decide which concrete class to instantiate. It lets a class defer instantiation to its subclasses while still coding against a common interface or abstract type.
Key Points: • A creator class declares an abstract or overridable factory method, often named create() or newInstance(). • Concrete subclasses override the factory method to instantiate a specific product type. • Client code depends only on the abstract product and creator types, not concrete classes. • It follows the open/closed principle: new product types can be added by creating new subclasses without editing existing code. • It's a narrower, single-product counterpart to the Abstract Factory pattern.
Example: A DocumentCreator base class might declare an abstract createDocument() method, with PdfCreator and WordCreator subclasses each returning their own Document implementation, so the rest of the application never needs to know which concrete class was produced.
Code Example:
abstract class DocumentCreator {
abstract Document createDocument();
}
class PdfCreator extends DocumentCreator {
Document createDocument() {
return new PdfDocument();
}
}
class WordCreator extends DocumentCreator {
Document createDocument() {
return new WordDocument();
}
}Interview Tip: A concise interview answer is:
"Factory Method defers object creation to subclasses by declaring a creation method in a base class that each subclass overrides to return its own concrete product, so client code can work with the abstract type without knowing exactly which class gets instantiated."