-
Notifications
You must be signed in to change notification settings - Fork 0
/
DIP.cpp
73 lines (58 loc) · 1.28 KB
/
DIP.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
66
67
68
69
70
71
72
73
//DIP = Dependancy Inversion Principle
//Strategy Design Pattern
//Runtime Polymorphism
#include<iostream>
#include<string>
//Abstraction
class IEngine {
public: virtual void start() = 0;
virtual void stop() = 0;
};
//Low Level Module
class MPFIEngine :public IEngine{
public:
void start() {}
void stop() {}
};
class GDIEngine:public IEngine {
public:
void start() {};
void stop() {};
};
//High Level Module
class XUV3X0 {
//Dependency(Abstract)
IEngine* engine;
public:
//Constructor dependency Injection
XUV3X0(IEngine* engineArg) :engine{ engineArg }{}
void drive()
{
this->engine->start();
std::cout<<"Engine started! \n";
}
void halt()
{
this->engine->stop();
std::cout<<"Engine stopped! \n";
}
//destructor
~XUV3X0() {
delete engine;//as the XUV3X0 and engine are Composition which is 'has-a relationship' which is a death relationship
}
};
class StallinEngine {
};
int main()
{
MPFIEngine napEngine;//naturally aspirated petrol engine
GDIEngine turboEngine;
XUV3X0 car{&napEngine};//base class ptr pointing to derived class object
car.drive();
XUV3X0 turboSeries{ &turboEngine };
car.drive();
car.halt();
return 0;
}
//Car uses Engine
//Car Depends on Engine