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

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. It's particularly useful in scenarios like data processing pipelines where you may need to switch between different processing strategies without modifying the client code. In this example, we'll implement a simple data pipeline using the Strategy Pattern in C++.

Example of Strategy Pattern in C++ Data Processing Pipeline


#include <iostream>
#include <vector>

// Strategy Interface
class DataProcessor {
public:
    virtual void process(std::vector& data) = 0;
    virtual ~DataProcessor() {}
};

// Concrete Strategy for Summation
class SumProcessor : public DataProcessor {
public:
    void process(std::vector& data) override {
        int sum = 0;
        for (int num : data) {
            sum += num;
        }
        std::cout << "Sum: " << sum << std::endl;
    }
};

// Concrete Strategy for AVERAGING
class AverageProcessor : public DataProcessor {
public:
    void process(std::vector& data) override {
        if (data.empty()) return;
        int sum = 0;
        for (int num : data) {
            sum += num;
        }
        double average = static_cast(sum) / data.size();
        std::cout << "Average: " << average << std::endl;
    }
};

// Context
class DataPipeline {
private:
    DataProcessor* processor;
public:
    void setProcessor(DataProcessor* p) {
        processor = p;
    }

    void execute(std::vector& data) {
        if (processor) {
            processor->process(data);
        }
    }
};

int main() {
    DataPipeline pipeline;

    std::vector data = {1, 2, 3, 4, 5};

    // Using SumProcessor
    SumProcessor sumProcessor;
    pipeline.setProcessor(&sumProcessor);
    pipeline.execute(data);

    // Using AverageProcessor
    AverageProcessor averageProcessor;
    pipeline.setProcessor(&averageProcessor);
    pipeline.execute(data);

    return 0;
}
    

Strategy Pattern C++ Data Processing Design Pattern Software Engineering