-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstrategy.cpp
76 lines (63 loc) · 1.46 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
/*!
* \brief Strategy. Define a family of algorithms, encapsulate each
* one, and make them interchangeable.
*
* Context -> Strategy
* | |
* ConcreteContext ConcreteStrategy1 ConcreteStrategy2
*/
#include <iostream>
class Strategy {
public:
virtual std::string Execute() = 0;
};
// ConcreteStrategy1.
class Walk : public Strategy {
public:
std::string Execute() {
return "<Walk>";
}
};
// ConcreteStrategy2.
class Swim :public Strategy {
public:
std::string Execute() {
return "<Swim>";
}
};
// Context.
class Context {
public:
virtual void SetStrategy(Strategy *w) = 0;
virtual void Go() = 0;
};
// ConcreteContext.
class Go2Beijing : public Context {
public:
Go2Beijing() : way_(0) {};
void SetStrategy(Strategy *w) {
way_ = w;
}
void Go() {
if(way_ != 0)
std::cout << "I'm going to " << way_->Execute().c_str() << " to Beijing." << std::endl;
else
std::cout << "I don't know how to get to Beijing yet." << std::endl;
}
private:
Strategy *way_;
};
int main() {
Strategy *swim = new Swim();
Strategy *walk = new Walk();
Context *context = new Go2Beijing();
context->Go();
std::cout << "/////////////////" << std::endl;
context->SetStrategy(swim);
context->Go();
std::cout << "/////////////////" << std::endl;
context->SetStrategy(walk);
context->Go();
std::cout << "/////////////////" << std::endl;
return 0;
}