When do I use abstract classes versus interfaces with regards to dependency Injection?

前端 未结 6 923
名媛妹妹
名媛妹妹 2021-02-08 18:23

I have been reading some articles about the SOLID principles and dependency Inversion. From my point of view, I must use an interface to talk to any class. My classes are chatti

6条回答
  •  我在风中等你
    2021-02-08 19:18

    The reason to choose an abstract class over an interface has to do with reusable code. The fact that you're using dependency injection doesn't change this answer.

    Do all of the subclasses have common functionality? If so, it can be defined in the base class.

    Should the template method design pattern be used? If so, the algorithm exists in the base class.

    As always, the answer is: "It depends." You can't do these approaches with interfaces as interfaces only specify the contract and don't have implementation. If the contract is all you need, then go with an interface. If you need code to be shared by the subclasses, then go with an abstract class.

提交回复
热议问题