1
1
#include < iostream>
2
2
#include < vector>
3
+ #include < string>
3
4
4
5
5
6
// ---- single responsibility principle (SRP)
@@ -159,24 +160,74 @@ class IMashine : public IPrinter, public IScanner{};
159
160
160
161
class Printer : public IPrinter {
161
162
public:
162
- void print (const Document &d){};
163
+ void print (const Document &d) override {};
163
164
};
164
165
165
166
class Scanner : public IScanner {
166
167
public:
167
- void scan (const Document &d){};
168
+ void scan (const Document &d) override {};
168
169
};
169
170
170
171
class Fax : public IFax {
171
172
public:
172
- void fax (const Document &d){};
173
+ void fax (const Document &d) override {};
173
174
};
174
175
175
176
class MultiMashine : public IMashine {
176
177
public:
177
- void print (const Document &d){};
178
- void scan (const Document &d){};
178
+ void print (const Document &d) override {};
179
+ void scan (const Document &d) override {};
179
180
};
180
181
// ------------------------------------------- //
181
182
182
- // ---- dependency inversion principle (DIP)
183
+ // ---- dependency inversion principle (DIP)
184
+ // High-level modules should not depend on low-level modules. Both should depend on abstractions.
185
+ // Abstractions should notdepend on details. Details should depend on abstractions.
186
+
187
+ enum class Relationship
188
+ {
189
+ parent,
190
+ child,
191
+ sibling
192
+ };
193
+
194
+ class Person
195
+ {
196
+ public:
197
+ std::string name;
198
+ };
199
+
200
+ class RelationshipBrowser {
201
+ public:
202
+ virtual std::vector<Person> find_all_children_of (const std::string &name) = 0;
203
+ };
204
+
205
+ class Relationships : public RelationshipBrowser { // low-level, depends on abstraction
206
+ public:
207
+ std::vector<std::tuple<Person, Relationship, Person>> relations;
208
+ void add_parent_and_child (const Person &parent, const Person &child){
209
+ relations.push_back ({parent, Relationship::parent, child});
210
+ relations.push_back ({child, Relationship::child, parent});
211
+ }
212
+ virtual std::vector<Person> find_all_children_of (const std::string &name) override {
213
+ std::vector<Person> result;
214
+ for (const auto & [first, rel, second] : relations){
215
+ if (first.name == name && rel == Relationship::parent)
216
+ {
217
+ result.push_back (second);
218
+ }
219
+ }
220
+ return result;
221
+ }
222
+ };
223
+
224
+ class Research // high-level
225
+ {
226
+ public:
227
+ Research (RelationshipBrowser &browser){ // depends on abstraction
228
+ for (const auto &child : browser.find_all_children_of (" John" )){ // "John" for example
229
+ std::cout << " John has a child called " << child->name << std::endl;
230
+ }
231
+ }
232
+ };
233
+ // ------------------------------------------- //
0 commit comments