The Strategy design pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
Here’s an example of how the Strategy pattern might be implemented in C++:
class Strategy {
public:
virtual void execute() = 0;
};
class ConcreteStrategyA : public Strategy {
public:
void execute() {
// Implementation for algorithm A
}
};
class ConcreteStrategyB : public Strategy {
public:
void execute() {
// Implementation for algorithm B
}
};
class Context {
private:
Strategy* strategy_;
public:
Context(Strategy* strategy) : strategy_(strategy) {}
void set_strategy(Strategy* strategy) {
strategy_ = strategy;
}
void execute_strategy() {
strategy_->execute();
}
};
In this example, the Strategy
class is an interface that defines the execute
method. The ConcreteStrategyA
and ConcreteStrategyB
classes are concrete implementations of the Strategy
class, each with its own implementation of the execute
method. The Context
class has a private member variable of type Strategy*
and a public execute_strategy
method that calls the execute
method on the current strategy. The Context
class also has a public set_strategy
method that allows the strategy to be changed at runtime.
This allows the client code to select and switch between different algorithms at runtime, depending on the requirements of the situation.