Avoiding parallel inheritance hierarchies

前端 未结 6 919
失恋的感觉
失恋的感觉 2020-12-01 04:46

I have two parallel inheritance chains:

Vehicle <- Car
        <- Truck <- etc.

VehicleXMLFormatter <- CarXMLFormatter
                    <-         


        
6条回答
  •  感情败类
    2020-12-01 04:50

    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
    {
    }
    

    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.

提交回复
热议问题