When I searched about it, it turned out Dependency Inversion is accomplished by using Dependency Injection
So I'm gonna use my own code about Dependency Injection. Please take a look at first this article, if you haven't read it yet
"😭 Escape from crazy boy friend!" explain Dependency Injection simplest way
Kaziu ・ Sep 4 '22
▼ Bad code in this article of Dependency Injection
class Woman {
makeLover(){
const bf = new CrazyMan()
bf.stayWith()
}
}
class CrazyMan {
stayWith() {
console.log('I am dangerous man, stay with me')
}
}
const woman = new Woman()
woman.makeLover()
image is like this. Woman depends on Crazy man
We need to invert this direction, but how?
It resolves by using interface, this is Dependency Inversion
class Woman {
constructor(man: IMan) {
this.man = man
}
makeLover(){
this.man.stayWith()
}
}
// ⭐⭐ this interface is key !!!!!!!
interface IMan {
stayWith: () => void
}
class CrazyMan {
stayWith() {
console.log('I am dangerous man, stay with me')
}
}
class GoodMan {
stayWith() {
console.log('I am good man, stay with me')
}
}
const man = new GoodMan()
const woman = new Woman(man)
woman.makeLover()
// I am good man, stay with me
▼ Now Crazy man, Good man depend on Man Interface, as you can see direction inverts now
ref
https://khalilstemmler.com/articles/tutorials/dependency-injection-inversion-explained/
This is good sample of Typescript, it's in japanese though
Top comments (0)