Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active April 10, 2024 08:02
Show Gist options
  • Save sunmeat/6d1223ca4efca9719a875c89e65b2103 to your computer and use it in GitHub Desktop.
Save sunmeat/6d1223ca4efca9719a875c89e65b2103 to your computer and use it in GitHub Desktop.
dependency inversion principle (dependency injection) cpp good example
#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