Factory Method Pattern Tutorial from Scratch (2026)
The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. This pattern delegates the instantiation logic to subclasses, promoting loose coupling and adhering to the Open/Closed Principle by allowing new product types without modifying existing creator code.
In this tutorial, you will implement the Factory Method pattern in Java and Python, exploring the creator interface, concrete creators, parameterized factories, and real-world applications like document editors and logging frameworks.
Creator Interface and Concrete Creators
The Creator class declares the factory method that returns Product objects. Subclasses override this method to create specific concrete products. This approach allows the client code to work with the Creator interface without knowing the concrete product types at compile time.
// Product interface
interface Document {
void open();
void save();
void close();
}
// Concrete products
class PDFDocument implements Document {
public void open() { System.out.println("Opening PDF document"); }
public void save() { System.out.println("Saving PDF document"); }
public void close() { System.out.println("Closing PDF document"); }
}
class WordDocument implements Document {
public void open() { System.out.println("Opening Word document"); }
public void save() { System.out.println("Saving Word document"); }
public void close() { System.out.println("Closing Word document"); }
}
// Creator with factory method
abstract class DocumentCreator {
public abstract Document createDocument();
public void processDocument() {
Document doc = createDocument();
doc.open();
doc.save();
doc.close();
}
}
class PDFCreator extends DocumentCreator {
public Document createDocument() { return new PDFDocument(); }
}
class WordCreator extends DocumentCreator {
public Document createDocument() { return new WordDocument(); }
}
Parameterized Factory Method
A parameterized factory method accepts an argument (typically a string or enum) to determine which concrete product to instantiate. This variation reduces the number of concrete creator classes needed and centralizes object creation logic in a single factory method.
enum DocumentType { PDF, WORD, HTML }
class DocumentFactory {
public static Document createDocument(DocumentType type) {
return switch (type) {
case PDF -> new PDFDocument();
case WORD -> new WordDocument();
case HTML -> new HTMLDocument();
};
}
}
// Usage
Document doc = DocumentFactory.createDocument(DocumentType.PDF);
doc.open();
Factory Method in Python
Python implements the Factory Method pattern naturally with its dynamic typing and first-class functions. The creator can accept a class reference or factory function, making the pattern more flexible and concise compared to Java's verbose class hierarchy.
from abc import ABC, abstractmethod
class Document(ABC):
@abstractmethod
def open(self): pass
class PDFDocument(Document):
def open(self):
print("Opening PDF document")
class WordDocument(Document):
def open(self):
print("Opening Word document")
class DocumentCreator(ABC):
@abstractmethod
def create_document(self) -> Document:
pass
def process_document(self):
doc = self.create_document()
doc.open()
class PDFCreator(DocumentCreator):
def create_document(self) -> Document:
return PDFDocument()
# Pythonic approach with function factory
def document_factory(doc_type: str) -> Document:
factories = {"pdf": PDFDocument, "word": WordDocument}
return factories[doc_type]()
Frequently Asked Questions
What is the difference between Factory Method and Simple Factory?
Simple Factory is a static method that creates objects based on parameters, while Factory Method defines an interface for creation that subclasses override. Factory Method is more flexible and adheres to the Open/Closed Principle by allowing new products without modifying existing code.
When should I use the Factory Method pattern?
Use Factory Method when a class cannot anticipate the class of objects it must create, when you want subclasses to specify the objects they create, or when you need to localize the logic of instantiation to avoid violating the Single Responsibility Principle.
Does Factory Method violate the Dependency Inversion Principle?
No, Factory Method actually supports it. The creator depends on the abstract product interface, and concrete creators depend on concrete products. Both high-level and low-level modules depend on abstractions.
Can Factory Method be used with dependency injection?
Yes, Factory Method works well alongside DI. You can inject the factory or the creator into client code, allowing tests to provide mock creators. Some DI frameworks can even generate factory implementations automatically.
Originally published on Ayodhyyya. Last updated June 1, 2026.