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

前端 未结 6 924
名媛妹妹
名媛妹妹 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 18:58

    An interface does not contain any implementation code and does not force the implementer to derive its implementation form a given class. A base class (abstract or not) can already contain some logic. This can be an advantage as well as an undesirable constraint.

    Of course you can combine both approaches. Define and program against an interface and at the same time provide a base class (or several base classes) implementing this interface and proving some basic logic that simplifies an implementers task. A person implementing the interface can decide to go the easy way and to extend a base class or to create something completely new and implement the interface directly.

    The .NET Framework class library provides base classes for collections like Collection or KeyedCollection both implementing IList that you can use as a base for creating your own specialized collection. But of course you can start from scratch and implement IList directly.

提交回复
热议问题