-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategy.cpp
More file actions
66 lines (54 loc) · 1.5 KB
/
Strategy.cpp
File metadata and controls
66 lines (54 loc) · 1.5 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
64
65
66
/**
* @cite Strategy Pattern states that the exact behavior of a system can be specified at runtime.
* Aims at promoting code reusability and flexibility by decoupling the
*
* @brief Strategy Pattern can be exemplified by a Sorting Class that can change the mode of sorting from Ascending and Descending.
*/
#include <algorithm>
#include <vector>
#include <iostream>
// Alternate Strategies for Sorting...
enum SortStrategies
{
asc,
desc
};
/**
* @brief Sorts the data based on the strategy provided.
*/
class Sorter
{
SortStrategies strategy;
public:
Sorter(SortStrategies s = SortStrategies::asc) : strategy(s) {}
// Sort the input based on the strategy...
void sort(std::vector<int> &arr)
{
if (strategy == SortStrategies::desc)
std::sort(arr.begin(), arr.end(), std::greater<int>());
else
std::sort(arr.begin(), arr.end(), std::less<int>());
}
// Set Strategy for the sorting...
void set_strategy(SortStrategies s)
{
strategy = s;
}
};
int main()
{
std::vector<int> a{2, 53, 23, 4, 34, 673, 2};
// Create Sorter with Ascending Strategy ...
Sorter sorter;
sorter.sort(a);
std::cout << "Ascending :: ";
for(auto it:a) std::cout << it << " ";
std::cout << std::endl;
// Set Descending Strategy ...
sorter.set_strategy(SortStrategies::desc);
sorter.sort(a);
std::cout << "Descending :: ";
for(auto it:a) std::cout << it << " ";
std::cout << std::endl;
return 0;
}