CreationalC++verifiedVerified

Factory Method Pattern in C++

Defines an interface for creating an object but lets subclasses decide which class to instantiate. Defers instantiation to subclasses.

How to Implement the Factory Method Pattern in C++

1Step 1: Define the Product interface

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

2Step 2: Concrete products

class Truck : public Transport {
public:
    std::string deliver() const override { return "Delivering by truck"; }
};

class Ship : public Transport {
public:
    std::string deliver() const override { return "Delivering by ship"; }
};

3Step 3: Define the Creator with the factory method

class Logistics {
public:
    virtual ~Logistics() = default;
    virtual std::unique_ptr<Transport> createTransport() const = 0;

    std::string planDelivery() const {
        auto transport = createTransport();
        return transport->deliver();
    }
};

4Step 4: Concrete creators override the factory method

class RoadLogistics : public Logistics {
public:
    std::unique_ptr<Transport> createTransport() const override {
        return std::make_unique<Truck>();
    }
};

class SeaLogistics : public Logistics {
public:
    std::unique_ptr<Transport> createTransport() const override {
        return std::make_unique<Ship>();
    }
};

5Step 5: Client code works with the Creator interface

int main() {
    std::unique_ptr<Logistics> logistics = std::make_unique<RoadLogistics>();
    std::cout << logistics->planDelivery() << "\n";

    logistics = std::make_unique<SeaLogistics>();
    std::cout << logistics->planDelivery() << "\n";
}

Factory Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Factory Method Pattern in the Real World

Think of a logistics company that ships packages. The headquarters defines the shipping process but doesn’t decide the vehicle. Regional offices (subclasses) choose whether to use trucks, ships, or drones based on local conditions. The headquarters just says ‘get me a transport’ and the regional office delivers the right one.