How do I implement the factory pattern in embedded devices with C++?

The Factory Pattern is a creational design pattern that allows for the creation of objects without specifying the exact class of object that will be created. This pattern is particularly useful in embedded systems where memory and resource constraints are critical, and the instantiation of object types can be abstracted away.

Implementing the Factory Pattern in Embedded Devices

In this example, we will implement a simple factory pattern in C++ for an embedded device. We will create two types of sensors: TemperatureSensor and PressureSensor. A factory class SensorFactory will be responsible for creating these sensor objects.


#include <iostream>

// Abstract Base Class
class Sensor {
public:
    virtual void read() = 0;
};

// Concrete Class for Temperature Sensor
class TemperatureSensor : public Sensor {
public:
    void read() override {
        std::cout << "Reading Temperature Sensor Data..." << std::endl;
    }
};

// Concrete Class for Pressure Sensor
class PressureSensor : public Sensor {
public:
    void read() override {
        std::cout << "Reading Pressure Sensor Data..." << std::endl;
    }
};

// Factory Class
class SensorFactory {
public:
    static Sensor* createSensor(const std::string& type) {
        if (type == "Temperature") {
            return new TemperatureSensor();
        } else if (type == "Pressure") {
            return new PressureSensor();
        }
        return nullptr;
    }
};

int main() {
    Sensor* tempSensor = SensorFactory::createSensor("Temperature");
    if (tempSensor) {
        tempSensor->read();
        delete tempSensor;  // Always free the memory
    }

    Sensor* pressureSensor = SensorFactory::createSensor("Pressure");
    if (pressureSensor) {
        pressureSensor->read();
        delete pressureSensor;  // Always free the memory
    }

    return 0;
}
    

Factory Pattern C++ Embedded Systems Sensor Management Design Patterns