Introduction to the Factory Method Pattern
Introduction to the Factory Method Pattern
Welcome back! So far, you’ve learned about the Singleton Pattern and have seen how it ensures a class has only one instance with a global access point. Now, we’re moving on to another essential creational design pattern: the Factory Method Pattern. This pattern is all about creating objects in a much more flexible way than direct instantiation.
What You'll Learn
In this lesson, you'll explore the Factory Method Pattern in C++. We'll cover the following key points:
- Understanding the Factory Method Pattern: Learn the core concepts and when to use this pattern.
- Implementing a Factory Method: Discover how to create your own factory methods to instantiate different types of objects.
- Flexibility and Extensibility: See how the Factory Method Pattern allows your code to handle new object types with ease.
Here's a glimpse of the code you’ll be working through:
document.hpp file that defines interface for product(Document) and concrete products(WordDocument, ExcelDocument):
document_creator.hpp file that defines interface for creator(DocumentCreator) and concrete creators(WordDocumentCreator, ExcelDocumentCreator):
main.cpp file that demonstrates the usage of the Factory Method Pattern:
This snippet demonstrates a simple implementation of the Factory Method Pattern using different document types. Let's break down the code and understand how the Factory Method Pattern works in practice:
- Document: An abstract base class representing a document interface with a pure virtual function
open(). This class defines the common behavior for all document types.- WordDocument and ExcelDocument: Concrete classes that implement the
Documentinterface with specificopen()functions for Word and Excel documents, respectively.
- WordDocument and ExcelDocument: Concrete classes that implement the
- DocumentCreator: An abstract base class for creating documents with a pure virtual function
createDocument(). This class acts as the factory method interface.- WordDocumentCreator and ExcelDocumentCreator: Concrete classes that implement the
DocumentCreatorinterface to create Word and Excel documents, respectively. In reality thecreateDocument()function would be a factory method that creates the specific document type with more complex initialization logic, but for simplicity, we're directly instantiating the document objects here.
- WordDocumentCreator and ExcelDocumentCreator: Concrete classes that implement the
- Main Function: Demonstrates how to use the factory method to create Word and Excel documents through the
DocumentCreatorinterface.
In short for the Factory Method Pattern we need a product interface (Document), concrete products (WordDocument, ExcelDocument), creator interface (DocumentCreator), and concrete creators (WordDocumentCreator, ExcelDocumentCreator) to create different types of products.
