Why C++ Programmers Should Study It
- Flexibility Allows dynamic swapping of algorithms based on runtime conditions.
- Encapsulation Encapsulates algorithm variations, making them interchangeable.
- Maintainability Simplifies maintenance by decoupling algorithm implementation from its context.
- Scalability Eases addition of new strategies without altering the context.
- Reusability Facilitates algorithm reuse across different contexts or applications.
- Testability Enhances testability by isolating the context from the strategy.
- Design Cleanliness Promotes cleaner design by separating concerns and reducing conditional statements.
// Abstract Strategy class
class Strategy {
public:
virtual ~Strategy() {}
virtual void execute() = 0;
};
ConcreteStrategyA.h
#include "Strategy.h"
// Concrete Strategy A class
class ConcreteStrategyA : public Strategy {
public:
void execute() override;
};
ConcreteStrategyB.h
#include "Strategy.h"
// Concrete Strategy B class
class ConcreteStrategyB : public Strategy {
public:
void execute() override;
};
Context.h
#include "Strategy.h"
// Context class
class Context {
public:
Context(Strategy* strategy);
void setStrategy(Strategy* strategy);
void executeStrategy();
private:
Strategy* strategy_;
};
Now let's implement these classes: ConcreteStrategyA.cpp
#include <iostream>
#include "ConcreteStrategyA.h"
void ConcreteStrategyA::execute() {
std::cout << "Executing Concrete Strategy A\n";
// Implementation of strategy A
}
ConcreteStrategyB.cpp</b>
#include <iostream>
#include "ConcreteStrategyB.h"
void ConcreteStrategyB::execute() {
std::cout << "Executing Concrete Strategy B\n";
// Implementation of strategy B
}
Context.cpp
#include "Context.h"
Context::Context(Strategy* strategy) : strategy_(strategy) {}
void Context::setStrategy(Strategy* strategy) {
strategy_ = strategy;
}
void Context::executeStrategy() {
if (strategy_)
strategy_->execute();
}
And finally,the main.cpp file:
main.cpp
#include <iostream>
#include "ConcreteStrategyA.h"
#include "ConcreteStrategyB.h"
#include "Context.h"
int main() {
ConcreteStrategyA strategyA;
ConcreteStrategyB strategyB;
Context context(&strategyA); // Start with strategy A
context.executeStrategy(); // Output should be "Executing Concrete Strategy A"
context.setStrategy(&strategyB); // Switch to strategy B
context.executeStrategy(); // Output should be "Executing Concrete Strategy B"
return 0;
}
The order to create the classes in your project would be:1. Strategy
2. ConcreteStrategyA
3. ConcreteStrategyB
4. Context
When you run the code, you should see the output:
Executing Concrete Strategy A Executing Concrete Strategy B>This demonstrates the Strategy design pattern, where the behavior of the `Context` object can be changed dynamically by switching between different `Strategy` objects.
No comments:
Post a Comment