Factory Method Pattern allows overriding to return different concrete object types

CK CK 3788 
Created at  
1,531 0 0

The Factory Method design pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. It defers instantiation to subclasses, allowing a class to delegate the instantiation logic to its subclasses, promoting loose coupling and making it easier to introduce new object types without modifying existing code.

The Factory Method design pattern is a creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. It's a way to defer instantiation to subclasses. Instead of directly creating objects within a class, a factory method is defined, which subclasses can override to return different concrete object types.
 

Factory Method Pattern allows overriding to return different concrete object types

 

Here's a breakdown of the key components and benefits:
 

Key Components:

  • Product: This is the interface or abstract class that defines the type of objects the factory method creates. Concrete products are the actual objects created.
  • Concrete Product: These are the classes that implement the Product interface. Each concrete product represents a specific variation of the object.
  • Creator: This is an abstract class or interface that declares the factory method. It may also implement a default factory method to provide a default product.
  • Concrete Creator: These are the subclasses of the Creator that implement the factory method to return specific Concrete Product objects.

How it works:
1. A client needs an object of a certain type.
2. The client interacts with the Creator class (or its subclass).
3. The Creator's factory method is called.
4. The Concrete Creator subclass's implementation of the factory method determines which Concrete Product to instantiate and return. The client receives the product without needing to know the specifics of its creation.
 

Example (Python):
Let's say we have a factory for creating different types of documents:
 

from abc import ABC, abstractmethod

# Abstract Product
class Document(ABC):
    @abstractmethod
    def open(self):
        pass

# Concrete Products
class PDFDocument(Document):
    def open(self):
        return "Opening a PDF document."

class WordDocument(Document):
    def open(self):
        return "Opening a Word document."

class TextDocument(Document):
    def open(self):
        return "Opening a Text document."

# Abstract Creator
class DocumentFactory(ABC):
    @abstractmethod
    def create_document(self) -> Document:
        pass

# Concrete Creators
class PDFDocumentFactory(DocumentFactory):
    def create_document(self) -> Document:
        return PDFDocument()

class WordDocumentFactory(DocumentFactory):
    def create_document(self) -> Document:
        return WordDocument()

class TextDocumentFactory(DocumentFactory):
    def create_document(self) -> Document:
        return TextDocument()

# Client Code
def open_document(factory: DocumentFactory):
    document = factory.create_document()
    print(document.open())

# Usage
if __name__ == "__main__":
    pdf_factory = PDFDocumentFactory()
    word_factory = WordDocumentFactory()
    text_factory = TextDocumentFactory()

    open_document(pdf_factory)  # Output: Opening a PDF document.
    open_document(word_factory)  # Output: Opening a Word document.
    open_document(text_factory)  # Output: Opening a Text document.

C++ Example

#include <iostream>
#include <memory>
#include <string>

// Abstract Product
class Document {
public:
    virtual void open() const = 0; // Pure virtual function
    virtual ~Document() = default;
};

// Concrete Products
class PDFDocument : public Document {
public:
    void open() const override {
        std::cout << "Opening a PDF document." << std::endl;
    }
};

class WordDocument : public Document {
public:
    void open() const override {
        std::cout << "Opening a Word document." << std::endl;
    }
};

class TextDocument : public Document {
public:
    void open() const override {
        std::cout << "Opening a Text document." << std::endl;
    }
};

// Abstract Creator
class DocumentFactory {
public:
    virtual std::unique_ptr<Document> createDocument() const = 0; // Factory Method
    virtual ~DocumentFactory() = default;
};

// Concrete Creators
class PDFDocumentFactory : public DocumentFactory {
public:
    std::unique_ptr<Document> createDocument() const override {
        return std::make_unique<PDFDocument>();
    }
};

class WordDocumentFactory : public DocumentFactory {
public:
    std::unique_ptr<Document> createDocument() const override {
        return std::make_unique<WordDocument>();
    }
};

class TextDocumentFactory : public DocumentFactory {
public:
    std::unique_ptr<Document> createDocument() const override {
        return std::make_unique<TextDocument>();
    }
};

// Client Code
void openDocument(const DocumentFactory& factory) {
    std::unique_ptr<Document> document = factory.createDocument();
    document->open();
}

// Main Function
int main() {
    PDFDocumentFactory pdfFactory;
    WordDocumentFactory wordFactory;
    TextDocumentFactory textFactory;

    openDocument(pdfFactory);  // Output: Opening a PDF document.
    openDocument(wordFactory); // Output: Opening a Word document.
    openDocument(textFactory); // Output: Opening a Text document.

    return 0;
}

 

Benefits:

  • Open/Closed Principle: You can introduce new types of products without modifying existing code. Simply create a new Concrete Creator and Concrete Product.
  • Loose Coupling: The client is decoupled from the concrete product classes.
  • Improved Code Organization: The instantiation logic is encapsulated within the factory, making the code cleaner and easier to maintain.
  • Flexibility: Allows easy switching between different product types without changing the client code.

 

When to use it:

  • When you want to create families of related objects without specifying their concrete classes.
  • When the creation logic should be encapsulated.
  • When you need to decouple client code from the concrete products being created.
  • When you anticipate the need to add new product types in the future.

The Factory Method pattern is a powerful tool for creating flexible and maintainable object-oriented code. It's especially useful when dealing with complex object creation scenarios where many different variations are possible.
 

Tags Creational Design Patterns Creational Patterns Factory Method Design Pattern Factory Method Pattern Sub Class Super Class Facebook X
Comments 0
Similar posts
  1. Software Design Patterns
    1,443
  2. Abstract Factory Pattern - Commonly Used for UI Themes or Objects
    1,470
  3. Builder Pattern - offering pre-defined Interfaces to set Individual Parts
    1,436
  1. The Blueprint of Success: Why System Design and Architecture Matter?
    408
  2. Software Design Patterns Cheat Sheet
    3,347
  3. Various naming for the Software Architecture - I can't find Component-based Architecture, Functional Architecture
    3,340
  4. Observer Pattern
    2,401
  5. Optimize the performance of a search results page that experiences high traffic
    146
  6. System Design: High-Traffic Time-Deal Promotion System
    181
  7. Designing Resilient Infrastructure to Prevent Order Data Loss During Kafka Failures
    161
  8. Real-Time Inventory & WMS System Design
    250
  9. Enterprise-Scale 100k+ TPS Order Tracking System Architecture
    210
  10. Enterprise-Scale 100k+ TPS Order Processing System Architecture
    183
  11. Architecting Dynamic Scale-Out and Scale-In with Docker Containers
    136
  12. How to Design Redis Caching in Infrastructure Architecture
    161
  13. Architecture Design - Database Partitioning vs. Sharding
    159
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,901
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232