The factory pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. It is particularly useful in data processing pipelines where you might have various stages of processing that require different classes of processors.
Here's a brief example of how to implement this pattern in a data processing context. In this example, we will create a pipeline that processes numerical and text data.
// Base Processor Interface
class Processor {
public:
virtual void process() = 0;
};
// Concrete Processor Classes
class NumberProcessor : public Processor {
public:
void process() override {
// Logic for processing numbers
std::cout << "Processing numbers..." << std::endl;
}
};
class TextProcessor : public Processor {
public:
void process() override {
// Logic for processing text
std::cout << "Processing text..." << std::endl;
}
};
// Factory Class
class ProcessorFactory {
public:
static Processor* createProcessor(const std::string& type) {
if (type == "number") {
return new NumberProcessor();
} else if (type == "text") {
return new TextProcessor();
}
return nullptr;
}
};
// Usage
int main() {
Processor* numberProcessor = ProcessorFactory::createProcessor("number");
numberProcessor->process();
Processor* textProcessor = ProcessorFactory::createProcessor("text");
textProcessor->process();
delete numberProcessor;
delete textProcessor;
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?