Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Factory and Abstract Factory Patterns in C++

Tech Nov 20 13

Introduction to Creational Patterns

In application architecture, creational patterns address object initialization mechanisms. Two prominent variations are the Factory Method and Abstract Factory patterns. These approaches encapsulate instantiation logic, allowing systems to remain flexible and adhere to the Open/Closed Principle by decoupling client code from concrete implementations.

The Factory Method Pattern

This pattern defines an interface for creating objects but delegates the actual instantiation decision to subclasses. By deferring this logic, the parent class remains unaware of the specific products being generated.

Potential Pitfalls

  • Simplification Overuse: Applying this pattern where simple constructors suffice can introduce unnecessary indirection and complexity.
  • Rigidity: Without proper abstraction, adding new product types might require altering existing factory logic, violating the prinicple of extensibility without modification.

Mitigation Strategies

  • Employ this pattern primarily when runtime polymorphism or configuration-driven creation is required.
  • Utilize inheritance hierarchies effectively to isolate changes within concrete factories.

Implementation Example

Below is a modern C++ approach utilizing smart pointers for memory management.

#include <iostream>
#include <memory>

// Base Interface for Report Components
class ReportComponent {
public:
    virtual ~ReportComponent() = default;
    virtual void render() const = 0;
};

// Concrete Implementation: Text Data
class TextReport : public ReportComponent {
public:
    void render() const override {
        std::cout << "Rendering plain text report." << std::endl;
    }
};

// Concrete Implementation: Graphical Data
class GraphReport : public ReportComponent {
public:
    void render() const override {
        std::cout << "Rendering graphical chart report." << std::endl;
    }
};

// Creator Interface
class ReportBuilder {
public:
    virtual std::unique_ptr<reportcomponent> buildComponent() const = 0;
    virtual ~ReportBuilder() = default;
};

// Concrete Creator: Standard Builder
class StandardBuilder : public ReportBuilder {
public:
    std::unique_ptr<reportcomponent> buildComponent() const override {
        return std::make_unique<textreport>();
    }
};

// Concrete Creator: Analytics Builder
class AnalyticsBuilder : public ReportBuilder {
public:
    std::unique_ptr<reportcomponent> buildComponent() const override {
        return std::make_unique<graphreport>();
    }
};

int main() {
    // Select builder dynamically
    std::unique_ptr<reportbuilder> builder = std::make_unique<standardbuilder>();
    
    // Create product via factory
    auto component = builder->buildComponent();
    
    if (component) {
        component->render();
    }
    
    return 0;
}</standardbuilder></reportbuilder></graphreport></reportcomponent></textreport></reportcomponent></reportcomponent></memory></iostream>

The Abstract Factory Pattern

While the Factory Method focuses on a single product type, the Abstract Factory enables the creation of families of related objects. It provides a surface for constructing multiple interdependent items without specifying their concrete classes.

Potential Pitfalls

  • Unnecessary Complexity: Creating families for unrelated components adds significant boilerplate overhead.
  • Scalability Issues: Introducing a new product variant often requires modifying the entire factory interface and all existing concrete factories.

Mitigation Strategies

  • Reserve this pattern for scenarios where consistency across multiple component types is critical (e.g., UI toolkits).
  • Design interfaces with clear separation to minimize impact when extending the product family.

Implementation Example

The following demonstrates a cross-platform UI theme system.

#include <iostream>
#include <memory>

// Product Family: Buttons
class ButtonWidget {
public:
    virtual ~ButtonWidget() = default;
    virtual void draw() const = 0;
};

class WinButton : public ButtonWidget {
public:
    void draw() const override {
        std::cout << "Drawing Windows-style button." << std::endl;
    }
};

class MacButton : public ButtonWidget {
public:
    void draw() const override {
        std::cout << "Drawing macOS-style button." << std::endl;
    }
};

// Product Family: Checkboxes
class CheckboxWidget {
public:
    virtual ~CheckboxWidget() = default;
    virtual void toggle() const = 0;
};

class WinCheckbox : public CheckboxWidget {
public:
    void toggle() const override {
        std::cout << "Toggling Windows-style checkbox." << std::endl;
    }
};

class MacCheckbox : public CheckboxWidget {
public:
    void toggle() const override {
        std::cout << "Toggling macOS-style checkbox." << std::endl;
    }
};

// Abstract Factory Interface
class UiThemeFactory {
public:
    virtual std::unique_ptr<buttonwidget> createButton() const = 0;
    virtual std::unique_ptr<checkboxwidget> createCheckbox() const = 0;
    virtual ~UiThemeFactory() = default;
};

// Concrete Factory: Windows Theme
class WinFactory : public UiThemeFactory {
public:
    std::unique_ptr<buttonwidget> createButton() const override {
        return std::make_unique<winbutton>();
    }
    std::unique_ptr<checkboxwidget> createCheckbox() const override {
        return std::make_unique<wincheckbox>();
    }
};

// Concrete Factory: Mac Theme
class MacFactory : public UiThemeFactory {
public:
    std::unique_ptr<buttonwidget> createButton() const override {
        return std::make_unique<macbutton>();
    }
    std::unique_ptr<checkboxwidget> createCheckbox() const override {
        return std::make_unique<maccheckbox>();
    }
};

int main() {
    // Instantiate specific theme factory
    std::unique_ptr<uithemefactory> platform = std::make_unique<macfactory>();
    
    // Generate family of objects
    auto btn = platform->createButton();
    auto chk = platform->createCheckbox();
    
    btn->draw();
    chk->toggle();
    
    return 0;
}</macfactory></uithemefactory></maccheckbox></checkboxwidget></macbutton></buttonwidget></wincheckbox></checkboxwidget></winbutton></buttonwidget></checkboxwidget></buttonwidget></memory></iostream>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.