-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cpp
66 lines (53 loc) · 1.28 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @FileName : strategy/main.cpp
* @CreateAt : 2022/4/18
* @Author : Inno Fang
* @Email : innofang@yeah.net
* @Description: Simple implementation of strategy pattern
*/
#include <iostream>
#include <string>
#include <vector>
class Strategy {
public:
virtual ~Strategy() = default;
virtual std::string take() = 0;
};
class BusStrategy : public Strategy {
public:
std::string take() override {
return "bus";
}
};
class CarStrategy : public Strategy {
public:
std::string take() override {
return "car";
}
};
class Context {
public:
Context(Strategy *strategy = nullptr) : _strategy(strategy) {}
~Context() {
delete _strategy;
}
void set_strategy(Strategy *strategy) {
delete _strategy;
_strategy = strategy;
}
void operation() {
std::cout << "Go outside and the transportation choice is [ " + _strategy->take() << " ].\n";
}
private:
Strategy *_strategy;
};
int main() {
Context *context = new Context(new BusStrategy);
std::cout << "==> Default transportation is bus.\n";
context->operation();
std::cout << "==> switch transportation from bus to car.\n";
context->set_strategy(new CarStrategy);
context->operation();
delete context;
return 0;
}