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++.
#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;
}
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?