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.
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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?