SOLID : Dependency Inversion
Kaziu
Posted on September 16, 2022
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
Posted on September 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.