"😭 Escape from crazy boy friend!" explain Dependency Injection simplest way

kaziusan

Kaziu

Posted on September 4, 2022

"😭 Escape from crazy boy friend!" explain Dependency Injection simplest way

🔥 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
Enter fullscreen mode Exit fullscreen mode

👦 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"
Enter fullscreen mode Exit fullscreen mode

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()
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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😎

💖 💪 🙅 🚩
kaziusan
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.

Related