I have two parallel inheritance chains:
Vehicle <- Car
<- Truck <- etc.
VehicleXMLFormatter <- CarXMLFormatter
<-
You could try to avoid inheritance for your formatters. Simply make a VehicleXmlFormatter
that can deal with Car
s, Truck
s, ... 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.