Menu
Coddy logo textTech

Factory & Abstract Factory

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 92 of 104.

The Factory pattern delegates object creation to a separate method or class, letting you create objects without specifying their exact class. This is useful when the creation logic is complex or when you want to decouple client code from concrete implementations.

A simple factory uses a method that returns different derived types based on input:

#include <iostream>
#include <memory>

class Button {
public:
    virtual void render() = 0;
    virtual ~Button() = default;
};

class WindowsButton : public Button {
public:
    void render() override { std::cout << "Windows button\n"; }
};

class MacButton : public Button {
public:
    void render() override { std::cout << "Mac button\n"; }
};

// Factory function
std::unique_ptr<Button> createButton(const std::string& os) {
    if (os == "windows") return std::make_unique<WindowsButton>();
    if (os == "mac") return std::make_unique<MacButton>();
    return nullptr;
}

The Abstract Factory takes this further by creating families of related objects. Instead of one factory method, you have a factory interface with multiple creation methods:

class Checkbox {
public:
    virtual void check() = 0;
    virtual ~Checkbox() = default;
};

class WindowsCheckbox : public Checkbox {
public:
    void check() override { std::cout << "Windows checkbox\n"; }
};

class MacCheckbox : public Checkbox {
public:
    void check() override { std::cout << "Mac checkbox\n"; }
};

// Abstract Factory
class GUIFactory {
public:
    virtual std::unique_ptr<Button> createButton() = 0;
    virtual std::unique_ptr<Checkbox> createCheckbox() = 0;
    virtual ~GUIFactory() = default;
};

class WindowsFactory : public GUIFactory {
public:
    std::unique_ptr<Button> createButton() override {
        return std::make_unique<WindowsButton>();
    }
    std::unique_ptr<Checkbox> createCheckbox() override {
        return std::make_unique<WindowsCheckbox>();
    }
};

Use Factory when you need flexible object creation, and Abstract Factory when you need to ensure that related objects work together consistently.

challenge icon

Challenge

Easy

Let's build a Document Generator system using the Factory and Abstract Factory patterns. You'll create a system that can generate different types of documents (reports and invoices) for different output formats (PDF and HTML), demonstrating how factories decouple object creation from client code.

You'll organize your code across four files:

  • Document.h: Define your document product hierarchy.

    Create an abstract base class Document with a pure virtual method generate() that returns a string describing the generated document, and a virtual destructor.

    Then create four concrete document classes:

    • PDFReportgenerate() returns "Generating PDF Report"
    • HTMLReportgenerate() returns "Generating HTML Report"
    • PDFInvoicegenerate() returns "Generating PDF Invoice"
    • HTMLInvoicegenerate() returns "Generating HTML Invoice"
  • DocumentFactory.h: Implement both a simple factory function and an abstract factory.

    First, create a simple factory function called createDocument that takes two strings: a document type ("report" or "invoice") and a format ("pdf" or "html"). It should return a std::unique_ptr<Document> pointing to the appropriate concrete document. Return nullptr for invalid combinations.

    Then create an abstract factory class called DocumentFactory with two pure virtual methods:

    • createReport() — returns a std::unique_ptr<Document>
    • createInvoice() — returns a std::unique_ptr<Document>

    Implement two concrete factories:

    • PDFFactory — creates PDFReport and PDFInvoice
    • HTMLFactory — creates HTMLReport and HTMLInvoice
  • DocumentService.h: Create a service that uses the abstract factory.

    Define a DocumentService class that takes a std::unique_ptr<DocumentFactory> in its constructor. It should have a method called generateAllDocuments() that uses the factory to create both a report and an invoice, then prints the result of calling generate() on each, one per line.

  • main.cpp: Demonstrate both factory approaches.

    Read two inputs:

    1. A document type (report or invoice)
    2. A format (pdf or html)

    First, use the simple factory function to create a document based on the inputs. Print the result of calling generate() on it.

    Then print a blank line.

    Next, create a DocumentService with the appropriate factory based on the format input (use PDFFactory for pdf, HTMLFactory for html). Call generateAllDocuments() to show how the abstract factory creates a family of related documents.

For example, with inputs report and pdf:

Generating PDF Report

Generating PDF Report
Generating PDF Invoice

With inputs invoice and html:

Generating HTML Invoice

Generating HTML Report
Generating HTML Invoice

Notice how the simple factory creates a single document based on both parameters, while the abstract factory ensures that all documents created by a service share the same format—this is the key benefit of Abstract Factory when you need families of related objects that work together consistently.

Cheat sheet

The Factory pattern delegates object creation to a separate method or class, allowing you to create objects without specifying their exact class. This decouples client code from concrete implementations.

A simple factory uses a function that returns different derived types based on input:

class Button {
public:
    virtual void render() = 0;
    virtual ~Button() = default;
};

class WindowsButton : public Button {
public:
    void render() override { std::cout << "Windows button\n"; }
};

class MacButton : public Button {
public:
    void render() override { std::cout << "Mac button\n"; }
};

// Factory function
std::unique_ptr<Button> createButton(const std::string& os) {
    if (os == "windows") return std::make_unique<WindowsButton>();
    if (os == "mac") return std::make_unique<MacButton>();
    return nullptr;
}

The Abstract Factory pattern creates families of related objects. Instead of one factory method, you have a factory interface with multiple creation methods:

class Checkbox {
public:
    virtual void check() = 0;
    virtual ~Checkbox() = default;
};

class WindowsCheckbox : public Checkbox {
public:
    void check() override { std::cout << "Windows checkbox\n"; }
};

class MacCheckbox : public Checkbox {
public:
    void check() override { std::cout << "Mac checkbox\n"; }
};

// Abstract Factory
class GUIFactory {
public:
    virtual std::unique_ptr<Button> createButton() = 0;
    virtual std::unique_ptr<Checkbox> createCheckbox() = 0;
    virtual ~GUIFactory() = default;
};

class WindowsFactory : public GUIFactory {
public:
    std::unique_ptr<Button> createButton() override {
        return std::make_unique<WindowsButton>();
    }
    std::unique_ptr<Checkbox> createCheckbox() override {
        return std::make_unique<WindowsCheckbox>();
    }
};

Use Factory when you need flexible object creation. Use Abstract Factory when you need to ensure that related objects work together consistently as a family.

Try it yourself

#include <iostream>
#include <string>
#include <memory>
#include "Document.h"
#include "DocumentFactory.h"
#include "DocumentService.h"

using namespace std;

int main() {
    // Read inputs
    string documentType;
    string format;
    cin >> documentType;
    cin >> format;
    
    // TODO: Use the simple factory function to create a document
    // based on documentType and format inputs
    // Print the result of calling generate() on it
    
    // Print a blank line
    cout << endl;
    
    // TODO: Create a DocumentService with the appropriate factory
    // based on the format input (PDFFactory for "pdf", HTMLFactory for "html")
    // Call generateAllDocuments() to demonstrate the abstract factory
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming