The purpose of interfaces continued

后端 未结 13 1403
轮回少年
轮回少年 2020-12-03 02:28

OK so I gather that Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance. Kind of like a contract.

13条回答
  •  春和景丽
    2020-12-03 02:43

    Using interfaces is more about giving the consuming code a way to know what you expect from it, rather than you needing to be concerned about the details of the consuming code.

    For example, one of the ways we use interfaces a lot is in our Business Layer / Data Access Layer.

    Because our business layer (BL) assembly will communicate with directly with the data access layer (DAL) assembly, the DAL cannot communicate directly with the BL. What happens if the DAL wants to use objects rather than individual fields? You would have to define your own DAL objects, and hydrate them with the input you've just received. Basically, a lot more work, more resources consumed, and multiple objects that represent the same data which makes for a maintenance nightmare.

    But, if you define interfaces in the DAL, you can tell consumers of the DAL what it expects. Then you can implement those interfaces in the BL and pass instances of the interfaces instead of BL objects.

    Interfaces are all about abstracting out the details of the implementation where they're not absolutely necessary.

    [Edit] If you have a lot of objects that do similar things, a combination of an interface and a base class with overridable/virtual methods might be more useful than just an interface.

提交回复
热议问题