-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy design pattern.cpp
More file actions
63 lines (52 loc) · 1.19 KB
/
Copy pathstrategy design pattern.cpp
File metadata and controls
63 lines (52 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
// Strategy Interface
class Strategy {
public:
virtual void execute() const = 0;
virtual ~Strategy() = default;
};
// Concrete Strategy A
class ConcreteStrategyA : public Strategy {
public:
void execute() const override {
cout << "Executing Strategy A" << endl;
}
};
// Concrete Strategy B
class ConcreteStrategyB : public Strategy {
public:
void execute() const override {
cout << "Executing Strategy B" << endl;
}
};
// Context
class Context {
private:
Strategy* strategy;
public:
Context(Strategy* strategy = nullptr) : strategy(strategy) {}
void setStrategy(Strategy* newStrategy) {
strategy = newStrategy;
}
void executeStrategy() const {
if (strategy) {
strategy->execute();
} else {
cout << "No strategy set" << endl;
}
}
};
// Client code
int main() {
Context context;
// Using Strategy A
ConcreteStrategyA strategyA;
context.setStrategy(&strategyA);
context.executeStrategy();
// Using Strategy B
ConcreteStrategyB strategyB;
context.setStrategy(&strategyB);
context.executeStrategy();
return 0;
}