The Factory Method is a creational design pattern that defines an interface for creating objects, but lets subclasses decide which class to instantiate. This pattern is useful when a class cannot anticipate the class of objects it needs to create or when you want to encapsulate object creation.
Key Concepts 📌
- Factory Method: A method that returns an instance of a class.
- Product: The object created by the factory method.
- Creator: The class that declares the factory method.
- Concrete Creator: Subclasses that implement the factory method to create specific products.
Example: Document Generator 📄
from abc import ABC, abstractmethod
# Product
class Document(ABC):
@abstractmethod
def generate(self):
pass
# Concrete Products
class PDFDocument(Document):
def generate(self):
return "Generating PDF document 📄"
class MarkdownDocument(Document):
def generate(self):
return "Generating Markdown document 📝"
# Creator
class DocumentFactory(ABC):
@abstractmethod
def create_document(self) -> Document:
pass
# Concrete Creators
class PDFFactory(DocumentFactory):
def create_document(self):
return PDFDocument()
class MarkdownFactory(DocumentFactory):
def create_document(self):
return MarkdownDocument()
# Usage
factory = PDFFactory()
doc = factory.create_document()
print(doc.generate()) # Output: Generating PDF document 📄
When to Use It ⚙️
- When you want to make subclasses decide which objects they create.
- When you need to extend the type of objects you create without modifying existing code.
- When you want to reduce the number of classes in your code.
For deeper insights into related patterns like Abstract Factory, check our tutorial: /en/tutorials/python_design_patterns/abstract_factory.
Benefits ✅
- Decouples client code from concrete classes.
- Promotes code reuse and flexibility.
- Simplifies object creation logic.
Let me know if you'd like to explore Python or Java implementations! 🐍💻