Solution: The Visitor pattern creates an external class that will use the data of the cart items to compute the postage.
1 2 3 | public interface Visitable { void accept(Visitor visitor); // implicitly public } |
1 2 3 4 5 | public class Book implements Visitable { @Override public void accept(Visitor visitor) { if (...) visitor.visit( this ); } } |
1 2 3 4 | public interface Visitor { void visit(Book book); // implicitly public void visit(CD cd); } |
1 2 3 4 5 6 7 8 9 10 11 | 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; } } |
1 2 3 4 5 6 7 8 9 | public class Client { public double calculatePostage() { PostageVisitor visitor = new PostageVisitor(); for (Visitable item : this .items) { item.accept(visitor); } return visitor.getTotalPostage(); } } |