-
Notifications
You must be signed in to change notification settings - Fork 5
/
strategy.cpp
65 lines (53 loc) · 1.5 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
// Strategy design pattern
#include <iostream>
#include <memory>
#include <string>
// strategy interface
struct IFlies {
virtual std::string fly() const = 0; // the algorithm (strategy)
virtual ~IFlies() = default;
};
// algorithm (strategy)
class Flies : public IFlies {
public:
std::string fly() const override { return "Flying high!"; }
};
// algorithm (strategy)
class CantFly : public IFlies {
public:
std::string fly() const override { return "Can't fly :("; }
};
// we implement the algorithm (strategy) via composition
class Animal {
private:
std::unique_ptr<IFlies> _flying_type;
public:
explicit Animal(std::unique_ptr<IFlies> flying_type)
: _flying_type{std::move(flying_type)} {}
void set_flying_ability(std::unique_ptr<IFlies> flying_type) {
_flying_type = std::move(flying_type);
}
void try_to_fly() const {
std::cout << '\t' << _flying_type->fly() << '\n';
}
};
class Dog : public Animal {
public:
Dog() : Animal(std::make_unique<CantFly>()) {}
};
class Bird : public Animal {
public:
Bird() : Animal(std::make_unique<Flies>()) {}
};
int main() {
Dog dog;
std::cout << "I'm a dog, trying to fly...\n";
dog.try_to_fly();
Bird bird;
std::cout << "I'm a bird, trying to fly...\n";
bird.try_to_fly();
// changing the algorithm (strategy) at runtime
std::cout << "I'm a bird, but changed my mind about flying...\n";
bird.set_flying_ability(std::make_unique<CantFly>());
bird.try_to_fly();
}