SOLID : Dependency Inversion

kaziusan

Kaziu

Posted on September 16, 2022

SOLID : Dependency Inversion

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

ā–¼ 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()
Enter fullscreen mode Exit fullscreen mode

image is like this. Woman depends on Crazy man

Image description

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

ā–¼ Now Crazy man, Good man depend on Man Interface, as you can see direction inverts now

Image description


ref
https://khalilstemmler.com/articles/tutorials/dependency-injection-inversion-explained/
This is good sample of Typescript, it's in japanese though

šŸ’– šŸ’Ŗ šŸ™… šŸš©
kaziusan
Kaziu

Posted on September 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Singleton Design Pattern in Typescript
typescript Singleton Design Pattern in Typescript

December 30, 2022

SOLID : Dependency Inversion
typescript SOLID : Dependency Inversion

September 16, 2022