-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_pattern.cpp
53 lines (40 loc) · 1.08 KB
/
strategy_pattern.cpp
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
#include <iostream>
#include <memory>
#include <utility>
class Strategy {
public:
virtual void execute() = 0; // (4)
virtual ~Strategy() {}
};
class Context {
std::unique_ptr<Strategy> strat{}; // (1)
public:
void setStrategy(std::unique_ptr<Strategy> strat_) { // (2)
strat = std::move(strat_); }
}
void strategy() { if (strat) strat->execute(); } // (3)
};
class Strategy1 : public Strategy {
public:
void execute() { std::cout << "Strategy1 executed\n"; }
};
class Strategy2 : public Strategy {
public:
void execute() { std::cout << "Strategy2 executed\n"; }
};
class Strategy3 : public Strategy {
public:
void execute() { std::cout << "Strategy3 executed\n"; }
};
int main()
{
std::cout << '\n';
Context k;
k.setStrategy(std::make_unique<Strategy1>());
k.strategy();
k.setStrategy(std::make_unique<Strategy2>());
k.strategy();
k.setStrategy(std::make_unique<Strategy3>());
k.strategy();
std::cout << '\n';
}