以前一个项目有一个基类:
class abstract CommonLogic
{
protected CommonLogic(IFirstLowLevelService firstService) {}
}
…几个开发人员想要子类化。 他们都相信控制反转原则,因此将所有依赖项作为构造函数参数。 有了 Autofac
,一个手边的依赖注入框架,他们冒险实现了许多伟大的子类。 其中一些看起来像这样:
class SpecificLogic : CommonLogic
{
public SpecificLogic(
IHighLevelService highLevelService,
IFirstLowLevelService firstService)
: base(firstService) {}
}
一切都很好,特殊逻辑类的变体数量不断增加和繁荣。
直到有一天,一位高级开发人员想要使用需要更多依赖项的新逻辑来扩展基类。 现在所有的子类也必须在它们的构造函数中包含新的依赖项,并将它们传递给基类。
class abstract CommonLogic
{
protected CommonLogic(
IFirstLowLevelService firstService,
ISecondLowLevelService secondService,
IThirdLowLevelService thirdService
) {}
}
class SpecificLogic : CommonLogic
{
public SpecificLogic(
IHighLevelService highLevelService,
IFirstLowLevelService firstService
ISecondLowLevelService secondService,
IThirdLowLevelService thirdService)
: base(firstService, secondService, thirdService) {}
}
这些更改在整个源码存储库中引起了很大的干扰,同时影响了生产代码和测试代码,延误了进度并使开发人员感到沮丧。
然后,一位勇敢的开发人员开始了将源头从黑暗中解放出来的任务。 他找到了聚合服务,一种承诺将子类未来更改与基类构造函数隔离开来的模式:
class abstract CommonLogic
{
public interface IAggregateService
{
IFirstLowLevelService FirstService {get;}
ISecondLowLevelService SecondService {get;}
IThirdLowLevelService ThirdService {get;}
}
protected CommonLogic(IAggregateService aggregateService) {}
}
class SpecificLogic : CommonLogic
{
public SpecificLogic(
IHighLevelService highLevelService,
IAggregateService aggregateService)
: base(aggregateService) {}
}
此外,通过利用 Castle DynamicProxy2
的强大功能,开发人员制作了一个可以动态生成聚合服务的设备,完全消除了为每个聚合服务接口实现类的负担。
最后,这位勇敢的冒险家找到了高级开发人员并展示了该模式,以及它如何仅通过将构造函数注入的依赖项聚合为一个依赖项来使他们摆脱困境。 看到它的辉煌,聚合服务模式在整个源码实施,为团队传播光明和欢乐。 现在只需更改 IAggregateService
接口即可对基类依赖项进行更改,而无需再对子类进行任何更改。