避免并行继承层次结构 [英] Avoiding parallel inheritance hierarchies
问题描述
我有两个平行的继承链:
I have two parallel inheritance chains:
Vehicle <- Car
<- Truck <- etc.
VehicleXMLFormatter <- CarXMLFormatter
<- TruckXMLFormatter <- etc.
我的经验是,并行继承层次结构随着它们的增长而成为一种维护问题。
My experience has been that parallel inheritance hierarchies can become a maintenance headache as they grow.
ie不要将 toXML(),toSoap(),toYAML()
方法添加到我的主要类中。
i.e. NOT adding toXML(), toSoap(), toYAML()
methods to my principal classes.
我如何避免并行继承层次结构而不破坏关注点分离的概念?
How do I avoid a parallel inheritance hierarchy without breaking the concept of separation of concerns?
推荐答案
我正在考虑使用访问者模式。
I am thinking of using the Visitor pattern.
public class Car : Vehicle
{
public void Accept( IVehicleFormatter v )
{
v.Visit (this);
}
}
public class Truck : Vehicle
{
public void Accept( IVehicleFormatter v )
{
v.Visit (this);
}
}
public interface IVehicleFormatter
{
public void Visit( Car c );
public void Visit( Truck t );
}
public class VehicleXmlFormatter : IVehicleFormatter
{
}
public class VehicleSoapFormatter : IVehicleFormatter
{
}
这样,您可以避免使用额外的继承树,并将格式化逻辑与您的车辆分开 - 类。
Offcourse,当你创建一个新的车辆时,你将不得不为Formatter接口添加另一个方法(并在formatter接口的所有实现中实现这个新方法)。
但是,我认为这比创建一个新的Vehicle类更好,并且对于你拥有的每个IVehicleFormatter,创建一个可以处理这种新型车辆的新类。
With this, you avoid an extra inheritance tree, and keep the formatting logic separated from your Vehicle-classes.
Offcourse, when you create a new vehicle, you'll have to add another method to the Formatter interface (and implement this new method in all the implementations of the formatter interface).
But, I think that this is better then creating a new Vehicle class, and for every IVehicleFormatter you have, create a new class that can handle this new kind of vehicle.
这篇关于避免并行继承层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!