forked from LC354364741/design-patterns-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrategy.cpp
97 lines (82 loc) · 1.45 KB
/
Strategy.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* C++ Design Patterns: Strategy
* Author: Jakub Vojvoda [github.com/JakubVojvoda]
* 2016
*
* Source code is licensed under MIT License
* (for more details see LICENSE)
*
*/
#include <iostream>
/*
* Strategy
* declares an interface common to all supported algorithms
*/
class Strategy
{
public:
virtual ~Strategy() { /* ... */ }
virtual void algorithmInterface() = 0;
// ...
};
/*
* Concrete Strategies
* implement the algorithm using the Strategy interface
*/
class ConcreteStrategyA : public Strategy
{
public:
~ConcreteStrategyA() { /* ... */ }
void algorithmInterface()
{
std::cout << "Concrete Strategy A" << std::endl;
}
// ...
};
class ConcreteStrategyB : public Strategy
{
public:
~ConcreteStrategyB() { /* ... */ }
void algorithmInterface()
{
std::cout << "Concrete Strategy B" << std::endl;
}
// ...
};
class ConcreteStrategyC : public Strategy
{
public:
~ConcreteStrategyC() { /* ... */ }
void algorithmInterface()
{
std::cout << "Concrete Strategy C" << std::endl;
}
// ...
};
/*
* Context
* maintains a reference to a Strategy object
*/
class Context
{
public:
Context( Strategy* const s ) : strategy( s ) {}
~Context()
{
delete strategy;
}
void contextInterface()
{
strategy->algorithmInterface();
}
// ...
private:
Strategy *strategy;
// ...
};
int main()
{
Context context( new ConcreteStrategyA() );
context.contextInterface();
return 0;
}