This is a good place for application of the Visitor
design pattern.
The beauty of this pattern is you can call unrelated code on different subclasses of a superclass without having to do weird casts everywhere or putting tons of unrelated methods into the superclass.
This works by creating a Visitor
object and allowing our Vehicle
class to accept()
the visitor.
You can also create many types of Visitor
and call unrelated code using the same methods, just a different Visitor
implementation, which makes this design pattern very powerful when creating clean classes.
A demo for example:
public class VisitorDemo {
// We'll use this to mark a class visitable.
public static interface Visitable {
void accept(Visitor visitor);
}
// This is the visitor
public static interface Visitor {
void visit(Boat boat);
void visit(Car car);
}
// Abstract
public static abstract class Vehicle implements Visitable {
// NO OTHER RANDOM ABSTRACT METHODS!
}
// Concrete
public static class Car extends Vehicle {
public void doCarStuff() {
System.out.println("Doing car stuff");
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
// Concrete
public static class Boat extends Vehicle {
public void doBoatStuff() {
System.out.println("Doing boat stuff");
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
// Concrete visitor
public static class StuffVisitor implements Visitor {
@Override
public void visit(Boat boat) {
boat.doBoatStuff();
}
@Override
public void visit(Car car) {
car.doCarStuff();
}
}
public static void main(String[] args) {
// Create our garage
Vehicle[] garage = {
new Boat(),
new Car(),
new Car(),
new Boat(),
new Car()
};
// Create our visitor
Visitor visitor = new StuffVisitor();
// Visit each item in our garage in turn
for (Vehicle v : garage) {
v.accept(visitor);
}
}
}
As you can see, StuffVisitor
allows you to call different code on Boat
or Car
depending on which implementation of visit
is called. You can also create other implementations of the Visitor to call different code with the same .visit()
pattern.
Also notice that using this method, there is no use of instanceof
or any hacky class checking. The only duplicated code between classes is the method void accept(Visitor)
.
If you want to support 3 types of concrete subclasses for example, you can just add that implementation into the Visitor
interface too.