-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
95 lines (83 loc) 路 2.33 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* eslint-disable @typescript-eslint/no-redeclare */
// Provider identifier style is like VSCode's implementation.
import {
createProviderIdentifier,
multiple,
rootContainer,
} from '@youmiya/core';
// First, we define interfaces and corresponding provider identifiers.
// define interfaces
interface IVocal {
sing(): void;
}
interface IDrummer {
playTheDrum(): void;
}
interface IGuitar {
playTheGuitar(): void;
}
interface IBass {
playTheBass(): void;
}
// define identifiers, which can has the same name as interface
const IVocal = createProviderIdentifier('Vocal');
const IDrummer = createProviderIdentifier('IDrummer');
const IGuitar = createProviderIdentifier('Guitar');
const IBass = createProviderIdentifier('IBass');
// Then we implements the classes for interfaces
class Soyo implements IBass {
playTheBass() {
console.log('Soyo is playing the bass.');
}
}
class Tomori implements IVocal {
sing() {
console.log('Tomori is singing.');
}
}
class Anon implements IGuitar {
playTheGuitar() {
console.log('Anon is playing the guitar.');
}
}
class Rana implements IGuitar {
playTheGuitar() {
console.log('Rana is playing the guitar.');
}
}
class Taki implements IDrummer {
playTheDrum() {
console.log('Taki is playing the drum.');
}
}
// The next step we need to bind provider identifier to the corresponding class implementation.
// Provider identifier can be used as InjectionToken.
rootContainer.register(IBass).toClass(Soyo);
rootContainer.register(IVocal).toClass(Tomori);
rootContainer.register(IGuitar).toClass(Anon);
rootContainer.register(IGuitar).toClass(Rana);
rootContainer.register(IDrummer).toClass(Taki);
// Then we can use them in out class...
class MyGO {
constructor(
@IBass() private bass: IBass,
@IGuitar() @multiple private guitars: IGuitar[],
@IDrummer() private drummer: IDrummer,
@IVocal() private vocal: IVocal,
) {}
live() {
this.bass.playTheBass();
this.guitars.forEach(guitar => guitar.playTheGuitar());
this.drummer.playTheDrum();
this.vocal.sing();
}
}
// You can still make class itself as InjectionToken
rootContainer.register(MyGO).toClass(MyGO);
const mygo = rootContainer.resolve(MyGO);
mygo.live();
// Soyo is playing the bass.
// Anon is playing the guitar.
// Rana is playing the guitar.
// Taki is playing the drum.
// Tomori is singing.