问题
I'm dealing with a Parallel Inheritance Hierarchy and I have an idea for a step by step refactoring and would like opinions on whether it will work or whether there is a better way to do it.
Create a Handler class with children that implement the specific behavior required e.g
CarHandler
with childrenvwHandler
,fordHandler
,bmwHandler
Add calls to all the components and restructure it so that the children return the objects neccessary. e.g. Call
vwHandler.getDrive
will return the result ofvwDrive.drive
, callvwHandler.getSeat
returnsvwSeat.seat
)Refactor the other classes so that they provide general functionality rather than specific e.g. Call
vwHandler.getDrive
will returndrive(vwSpec1, vwSpec2)
Example of Handler
public abstract class CarHandler
{
private Car car;
public Car getCar()
{
return car;
}
public Car setCar()
{
car = car;
}
public CarHandler(Car car)
{
this.car = car;
}
public Car getCar()
{
return car;
}
public void setCar(Car car)
{
this.car = car;
}
public void updateCar()
{
Globalizer.updateOnServer(car);
}
public abstract Drive getNewDrive();
public abstract Seat getNewSeat();
}
回答1:
I don't really understand your problem, as I don't see the relation of your example to a parallel inheritance hierarchy, but I don't like the protected field car in your approch.
For a few more details see my answer here. The accepted answer there is a good example of how to encapsulate behaviour in the base class.
回答2:
This approach is working quite well for me actually, I've implemented the first two steps and ended up removing several hundred lines of duplication as well as getting a good look at how to further refactor in future. I would highly recommend this approach.
来源:https://stackoverflow.com/questions/8938320/parallel-inheritance-hierarchy-refactoring