-
Notifications
You must be signed in to change notification settings - Fork 1
/
strategy-pattern.cc
90 lines (76 loc) · 1.57 KB
/
strategy-pattern.cc
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
#include <iostream>
// Helper function.
template<typename ...Ts>
void println(Ts ...args) {
((std::cout << args), ...) << std::endl;
}
// struct Car {
// virtual void brake() = 0;
// virtual ~Car() {}
// };
// struct Sedan : Car {
// void brake() override {
// println("Simple Brake Applied.");
// }
// };
// struct SUV : Car {
// void brake() override {
// println("ABS Brake Applied.");
// }
// };
// struct Sports : Car {
// void brake() override {
// println("Simple Brake Applied.");
// }
// };
// int main() {
// Sedan {}.brake();
// return 0;
// }
struct Brake {
virtual void execute() = 0;
virtual ~Brake() {}
};
struct SimpleBrake : Brake {
void execute() override {
println("Simple Brake Applied.");
}
};
struct ABSBrake : Brake {
void execute() override {
println("ABS Brake Applied.");
}
};
struct Car {
explicit Car(Brake* brake) : brakeSystem(brake) {}
virtual void brake() = 0;
virtual ~Car() {}
protected:
Brake* brakeSystem; // Composition.
};
struct Sedan : Car {
explicit Sedan(Brake* brake) : Car(brake) {}
void brake() override {
brakeSystem->execute();
}
};
struct SUV : Car {
explicit SUV(Brake* brake) : Car(brake) {}
void brake() override {
brakeSystem->execute();
}
};
struct Sports : Car {
explicit Sports(Brake* brake) : Car(brake) {}
void brake() override {
brakeSystem->execute();
}
};
int main() {
SimpleBrake simpleBrake;
ABSBrake absBrake;
Sedan { &absBrake }.brake();
SUV { &simpleBrake }.brake();
Sports { &simpleBrake }.brake();
return 0;
}