-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathInversion_of_control.js
55 lines (46 loc) · 1.36 KB
/
Inversion_of_control.js
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
// IoC Container Example
export default class Container {
constructor() {
this._services = new Map();
this._singletons = new Map();
}
register(name, definition, dependencies) {
this._services.set(name, {definition: definition, dependencies: dependencies})
}
singleton(name, definition, dependencies) {
this._services.set(name, {definition: definition, dependencies: dependencies, singleton:true})
}
get(name) {
const c = this._services.get(name);
if(this._isClass(c.definition)) {
if(c.singleton) {
const singletonInstance = this._singletons.get(name);
if(singletonInstance) {
return singletonInstance
} else {
const newSingletonInstance = this._createInstance(c);
this._singletons.set(name, newSingletonInstance);
return newSingletonInstance;
}
}
return this._createInstance(c);
} else {
return c.definition;
}
}
_getResolvedDependencies(service) {
let classDependencies = [];
if(service.dependencies) {
classDependencies = service.dependencies.map((dep) => {
return this.get(dep)
})
}
return classDependencies;
}
_createInstance(service) {
return new service.definition(...this._getResolvedDependencies(service))
}
_isClass(definition) {
return typeof definition === 'function'
}
}