Visitor
Example - Shopping cart
interface Visitorable {
int accept(Visitor visitor);
}
interface Visitor {
int getWeight(Apple apple);
int getWeight(Banana banana);
}
class VisitorImpl implements Visitor {
@Override
public int getWeight(Apple apple) {
return apple.getWeight();
}
@Override
public int getWeight(Banana banana) {
return banana.getWeight();
}
}
class Apple implements Visitorable {
private int weight;
public Apple(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
@Override
public int accept(Visitor visitor) {
return visitor.getWeight(this);
}
}
class Banana implements Visitorable {
private int weight;
public Banana(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
@Override
public int accept(Visitor visitor) {
return visitor.getWeight(this);
}
}Last updated