-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy.cpp
78 lines (68 loc) · 1.6 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
#include <iostream>
#include <string_view>
/***
The Startegy interface declares operations common to all supported versions
of some algorithm.
***/
class Strategy
{
public:
virtual ~Strategy() {};
virtual void doAlgorithm(std::string_view data) const = 0;
};
/***
The Context maintains a reference to one of the Strategy objects.
***/
class Context
{
private:
Strategy* _strategy{nullptr};
public:
explicit Context(Strategy *strategy)
: _strategy(strategy)
{}
void setStrategy(Strategy *strategy)
{
if(_strategy) delete _strategy;
_strategy = strategy;
}
void doSomeBusinessLogic() const
{
_strategy->doAlgorithm("dbcea");
}
};
/***
Concrete Strategies implement the algorithm following the base Strategy interface.
***/
class ConcreteStrategy1: public Strategy
{
public:
void doAlgorithm(std::string_view data) const override
{
std::string result(data);
std::sort(result.begin(), result.end());
std::cout << result << std::endl;
}
};
class ConcreteStrategy2: public Strategy
{
public:
void doAlgorithm(std::string_view data) const override
{
std::string result(data);
std::sort(result.begin(), result.end(), std::greater<>());
std::cout << result << std::endl;
}
};
/***
The client code picks a concrete strategy and passes it to the context.
***/
int main()
{
Context* context = new Context(new ConcreteStrategy1());
context->doSomeBusinessLogic();
context->setStrategy(new ConcreteStrategy2());
context->doSomeBusinessLogic();
delete context;
return 0;
}