在基类上向构造函数添加新参数意味着我必须重构所有从其继承的类? [英] Adding a new parameter to constructor on the base class means I have to refactor all of the classes that inherit from it?
问题描述
我正在使用控制容器的温莎城堡反转。
I am using Castle Windsor Inversion of Control Container.
我发现,如果需要通过基类上的构造函数注入新组件,则全部从其继承的子类需要将该组件传递给基础的构造函数。
I have found that if I need to inject a new component via the constructor on the base class, then all child classes inheriting from it need to pass that component to the base's constructor. This is expected.
但是,如果我有数十个从该基类继承的孩子,以及数十个实例化这些孩子类的单元测试,该怎么办?我真的需要遍历并重构所有这些构造函数以及对这些构造函数的调用吗?我是否缺少一种设计模式,该模式将允许我轻松地修改基类构造函数,而不必随后重构该类的所有子级?
But what if I have dozens of children inheriting from that base class, and dozens of unit tests instantiating those child classes. Do I really need to go through and refactor all those constructors and calls to those constructors? Am I missing a design pattern that would allow me to easily modify a base class constructor without having to then refactor all the children of that class?
推荐答案
我认为,直接解决您的问题的方法是将基类的依赖关系打包为新类,例如 BaseDependencies
,该基类依赖于该新类。在这种情况下,如果基类有新的依赖关系,则只需向 BaseDependencies
添加一个新成员。
代码如下:
I think a direct solution to your problem would be packing up the dependencies of the base class to a new class like BaseDependencies
on which the base class depends on, in this case, you just need to add a new member to BaseDependencies
if there is a new dependency for the base class.
The code would be something like this:
class Base {
public Base(BaseDependencies d) {}
}
class BaseDependencies {
public DependencyA {get; set;}
public DependencyB {get; set;}
public DependencyC {get; set;}
}
另一个选择可能是重构代码以按类重用逻辑组成而不是继承。
请参阅: https://en.wikipedia.org/wiki/Composition_over_inheritance
The other option might be refactoring your code to reuse logic by class composition instead of inheritance. see: https://en.wikipedia.org/wiki/Composition_over_inheritance
这篇关于在基类上向构造函数添加新参数意味着我必须重构所有从其继承的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!