Saturday, January 21, 2012

The Visitor pattern

Problem: Determine the postage for the items in a shopping cart.
Solution: The Visitor pattern creates an external class that will use the data of the cart items to compute the postage.
public interface Visitable {
    void accept(Visitor visitor); // implicitly public
}
public class Book implements Visitable {
    @Override public void accept(Visitor visitor) {
        if (...) visitor.visit(this);
    }
}
public interface Visitor {
    void visit(Book book); // implicitly public
    void visit(CD cd);
}
public class PostageVisitor implements Visitor {
    @Override public void visit(Book book) {
        this.totalPostage += ...;
    }
    @Override public void visit(CD cd) {
        this.totalPostage += ...;
    }
    public void getTotalPostage() {
        return this.totalPostage;
    }
}
public class Client {
    public double calculatePostage() {
        PostageVisitor visitor = new PostageVisitor();
        for (Visitable item : this.items) {
            item.accept(visitor);
        }
        return visitor.getTotalPostage();
    }
}