Search code examples
javadesign-patternsfactory-patterndelegation

Design Patterns: Reduce duplicate code from 2 methods that is almost the same in java


I have several classes of vehicles such as truck, sedan, van, motorcycle. The common thing between them is that they all move, so I delegate it to a move class which contains these methods:

getSpeed()
setSpeed()
getDestination()
setDestination()
..
..
..
move()

Some vehicles move differently then others so I make a factory design pattern for it. So if it is it a car(truck,sedan, van) it would delegate to the MoveCarImpl class or if it is a motorcycle, it would delegate to the MoveBikeImpl class. My issue is. the bike and car has almost exactly the same move() algorithm. The only difference is that the bike algorithm calls 1 additional method at the end of move() method while car's move() algorithm doesn't. So now I have a lot of duplication of code in the MoveCarImpl class and MoveBikeImpl class. Any ideas on how to deal with this?


Solution

  • You can extend your car move implementation class with the bike move implementation class and override the move method.