DEV Community

Kaziu
Kaziu

Posted on • Edited on

"😭 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😎

Top comments (0)