CreationalC++verifiedVerified

Abstract Factory Pattern in C++

Provides an interface for creating families of related objects without specifying their concrete classes.

How to Implement the Abstract Factory Pattern in C++

1Step 1: Define abstract product interfaces

class Button {
public:
    virtual ~Button() = default;
    virtual std::string render() const = 0;
};

class Checkbox {
public:
    virtual ~Checkbox() = default;
    virtual std::string render() const = 0;
};

2Step 2: Define the abstract factory

class UIFactory {
public:
    virtual ~UIFactory() = default;
    virtual std::unique_ptr<Button> createButton() const = 0;
    virtual std::unique_ptr<Checkbox> createCheckbox() const = 0;
};

3Step 3: Concrete products for Light theme

class LightButton : public Button {
public:
    std::string render() const override { return "[Light Button]"; }
};
class LightCheckbox : public Checkbox {
public:
    std::string render() const override { return "[Light Checkbox]"; }
};

4Step 4: Concrete products for Dark theme

class DarkButton : public Button {
public:
    std::string render() const override { return "[Dark Button]"; }
};
class DarkCheckbox : public Checkbox {
public:
    std::string render() const override { return "[Dark Checkbox]"; }
};

5Step 5: Concrete factories

class LightThemeFactory : public UIFactory {
public:
    std::unique_ptr<Button> createButton() const override {
        return std::make_unique<LightButton>();
    }
    std::unique_ptr<Checkbox> createCheckbox() const override {
        return std::make_unique<LightCheckbox>();
    }
};

class DarkThemeFactory : public UIFactory {
public:
    std::unique_ptr<Button> createButton() const override {
        return std::make_unique<DarkButton>();
    }
    std::unique_ptr<Checkbox> createCheckbox() const override {
        return std::make_unique<DarkCheckbox>();
    }
};

6Step 6: Client code uses only the factory interface

void buildUI(const UIFactory& factory) {
    auto btn = factory.createButton();
    auto chk = factory.createCheckbox();
    std::cout << btn->render() << " " << chk->render() << "\n";
}

int main() {
    LightThemeFactory lightFactory;
    DarkThemeFactory darkFactory;

    buildUI(lightFactory);
    buildUI(darkFactory);
}

Abstract Factory Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Abstract Factory Pattern in the Real World

Imagine furnishing a room from IKEA versus a luxury boutique. Each store (factory) produces a complete set of furniture — chairs, tables, sofas — that share a consistent style. You pick the store, and every piece you get matches. You never mix a rustic IKEA chair with a baroque boutique table.