Last active
April 10, 2024 08:02
-
-
Save sunmeat/6d1223ca4efca9719a875c89e65b2103 to your computer and use it in GitHub Desktop.
dependency inversion principle (dependency injection) cpp good example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
__interface IService { | |
void ProvideService(); | |
}; | |
class Police : public IService { | |
// ... | |
void ProvideService() override { | |
cout << "Успокаиваю буйных соседей...\n"; | |
} | |
}; | |
class Doctor : public IService { | |
// ... | |
void ProvideService() override { | |
cout << "Выписываю рецепт на аспирин...\n"; | |
} | |
}; | |
// class Fireman, PizzaCourier, Plumber, Electrician, InternetProvider etc | |
class Person { | |
IService* worker = nullptr; | |
public: | |
void SelectService(IService* injected_worker) { | |
worker = injected_worker; // low coupling - привязка к типу абстракции | |
} | |
~Person() { | |
// no need to do delete here! | |
} | |
void SolveProblem() { | |
if (worker != nullptr) | |
worker->ProvideService(); | |
} | |
}; | |
int main() { | |
setlocale(0, ""); | |
Person person; | |
IService* service = new Doctor; | |
person.SelectService(service); | |
person.SolveProblem(); | |
delete service; | |
service = new Police; | |
person.SelectService(service); | |
person.SolveProblem(); | |
delete service; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment