How do I implement the factory pattern in data processing pipelines with C++?

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.

Factory Pattern Implementation in Data Processing Pipelines

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; }

factory pattern data processing pipeline C++ factory pattern design patterns creational patterns