-
Notifications
You must be signed in to change notification settings - Fork 0
/
dependency-inversion-principle.ts
66 lines (58 loc) · 2.07 KB
/
dependency-inversion-principle.ts
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
/**
* **Dependency Inversion Principle**
*
* This one is strong! It may also be one of the harder ones to
* pull off correctly.
*
* Following the Dependency Inversion Principle means
* 1. Relying on contracts and interfaces rather than concrete implementations.
* This is, of course, very similar to the Interface Segregation Principle,
* which if you've followed it, will mean you have interfaces you can
* rely on.
* 2. High–level modules should not depend on lower-level modules; both
* depend on abstractions.
*
* In the example you'll see how all food providers have a common interface
* that they implement. So far so good.
*
* The dependency inversion happens as our high-level modules (the respective
* `FoodProvider`-derived classes) depends only on the `FoodProvider` interface.
* The `Foodie`, in turn, only expects to be provided with a concretion to use.
*
* We actually even do dependency injection in the `Foodie` class, since
* we provide it a `FoodProvider` instance. This enables a more flexible and
* testable system, as we can easily adapt and expand the `FoodProvider`s from the
* outside, even (for example) injecting fake databases into repository implementations
* or other cases that are typically hard to test without infrastructure.
*
* @see https://en.wikipedia.org/wiki/Dependency_inversion_principle
*/
function dipDemo() {
interface FoodProvider {
provideFood(): void;
}
class PizzaRestaurant implements FoodProvider {
provideFood(): void {
console.log("Man, that's some tasty pizza!");
}
}
class IceCreamTruck implements FoodProvider {
provideFood(): void {
console.log('Some sick ice cream!');
}
}
class Foodie {
private foodProvider: FoodProvider;
constructor(foodProvider: FoodProvider) {
this.foodProvider = foodProvider;
}
consumeFood(): void {
this.foodProvider.provideFood();
}
}
const pizzaLover = new Foodie(new PizzaRestaurant());
pizzaLover.consumeFood();
const icecreamLover = new Foodie(new IceCreamTruck());
icecreamLover.consumeFood();
}
dipDemo();