The Factory Pattern is a creational design pattern that provides an object-oriented way to create objects. It allows you to define an interface for creating objects, but lets subclasses decide which class to instantiate. This pattern is useful when you need to create objects without specifying the exact class or when dealing with complex object creation logic.
Key Concepts
- Factory Method: A method that returns an object of a class, typically subclasses override this to change the type of object being created.
- Abstract Product: A class that defines the interface of the objects being created.
- Concrete Product: Implements the abstract product interface.
- Client: Uses the factory to create objects without knowing the exact class.
Use Cases
- Creating objects that are platform-independent (e.g.,
software_development
) - Simplifying the creation of complex objects (e.g.,
system_architecture
) - Managing a large number of related classes (e.g.,
framework_design
)
Pros & Cons
✅ Pros:
- Decouples client code from concrete classes
- Promotes code reuse and flexibility
- Easier to add new types of objects
❌ Cons:
- Can lead to increased complexity if overused
- May require more boilerplate code
Example Code
class Document:
def open(self):
pass
class PDFDocument(Document):
def open(self):
return "Opening PDF file"
class WordDocument(Document):
def open(self):
return "Opening Word file"
class DocumentFactory:
def create_document(self, type):
if type == "pdf":
return PDFDocument()
elif type == "word":
return WordDocument()
else:
raise ValueError("Invalid document type")
# Usage
factory = DocumentFactory()
doc = factory.create_document("pdf")
print(doc.open())
Expand Your Knowledge
For a deeper dive into design patterns, check out our Design Patterns Series. 🚀
Let me know if you'd like to explore other patterns like singleton
or builder
! 🧱