概述
我正在开发一个使用两个主要抽象级别的应用程序:
- 核心库定义了许多接口,并包含根据接口实现核心功能的类。这样,我希望将核心算法编写一次,但使其适用于任意数量的接口实现。
- “实现”库使用第三方 SDK提供一组接口的一个特定实现。最终,这些图书馆将不止一个;使用哪一个将由配置决定。
应用程序本身从 SDK 库中实例化类并使用它们来满足核心库的依赖关系。
问题
我需要解决的问题一般是这样的:
// Algorithm in the core (interfaces are all implemented by the SDK library):
ICorrespondentRepository allCorrespondents = ...;
ICorrespondent correspondent = allCorrespondents.FindByName(...);
...
IDocumentRepository allDocuments = ...;
IDocument document = allDocuments.FindByTitle(...);
// Problem: Implementation needs state not exposed
// on ICorrespondent in order to do this:
document.SetRecipient(correspondent);
换句话说: anIDocument
可以将其接收者设置为先前获得的ICorrespondent
. 当SetRecipient
被调用时,IDocument
需要与 - 关联但不被 - 暴露的状态(对核心不重要的主键)的实现ICorrespondent
,以便实际影响更改。
一种方法是向下转换ICorrespondent
为内部的实际实现类SetRecipient
,但这感觉非常笨拙。更糟糕的是保留从接口引用到内部状态的映射。
问题的根源似乎是接口专门为核心库的通用需求而设计,尽管它们实际上有两个具有不同需求的消费者:核心和产生它们的实现库。
有没有更好的方法来重新设计这种需求?