"😠Escape from crazy boy friend!" explain Dependency Injection simplest way
Kaziu
Posted on September 4, 2022
🔥 Dangerous situation
Woman has crazy boy friend, but she can't escape from him. She doesn't have other choice.
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()
// I am dangerous man, stay with me
👦 There is good man !!
create GoodMan class
class Woman {
makeLover(){
const bf = new CrazyMan()
bf.stayWith()
}
}
class CrazyMan {
stayWith() {
console.log('I am dangerous man, stay with me')
}
}
// good man !!!!!!!
class GoodMan {
stayWith() {
console.log('I am good man, stay with me')
}
}
const woman = new Woman()
woman.makeLover()
// 😰 But still she stays with dangerous man
// "I am dangerous man, stay with me"
Why she still stays with dangerous man ??
because she (Woman class) depends on dangerous man
class Woman {
makeLover(){
// here, crazy man exists in Woman class, he is aaaaaaalways with her
const bf = new CrazyMan()
bf.stayWith()
}
}
So help her !! What should we do ???
class Woman {
// She does not depend on crazy man, she has choice now !!
constructor(man) {
this.man = man
}
makeLover(){
this.man.stayWith()
}
}
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
We could help her by erasing dependency on crazy man 😀
This is simplest way to explain, from now you could easily get other articles about Dependency Injection😎
💖 💪 🙅 🚩
Kaziu
Posted on September 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.