Avoiding parallel inheritance hierarchies

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

I have two parallel inheritance chains:

Vehicle <- Car
        <- Truck <- etc.

VehicleXMLFormatter <- CarXMLFormatter
                    <-         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 04:54

    You could try to avoid inheritance for your formatters. Simply make a VehicleXmlFormatter that can deal with Cars, Trucks, ... Reuse should be easy to achieve by chopping up the responsibilities between methods and by figuring out a good dispatch-strategy. Avoid overloading magic; be as specific as possible in naming methods in your formatter (e.g. formatTruck(Truck ...) instead of format(Truck ...)).

    Only use Visitor if you need the double dispatch: when you have objects of type Vehicle and you want to format them into XML without knowing the actual concrete type. Visitor itself doesn't solve the base problem of achieving reuse in your formatter, and may introduce extra complexity you may not need. The rules above for reuse by methods (chopping up and dispatch) would apply to your Visitor implementation as well.

提交回复
热议问题