Skip to content

Instantly share code, notes, and snippets.

@ryancutter
Created June 14, 2015 21:28
Show Gist options
  • Save ryancutter/0393b5a40883efbf005b to your computer and use it in GitHub Desktop.
Save ryancutter/0393b5a40883efbf005b to your computer and use it in GitHub Desktop.
// We have a lot of residences in our portfolio. There would probably be many methods in addition to this one.
public class Residence {
// Accept a visitor object so it can do something
void accept(Visitor visit);
}
// We have detached houses
public class DetachedHouse implements Residence {
// imagine getters and setters for these values
private double squareFeet;
private int lotSizeFeet;
@Override
public void accept(final ResidenceVisitor visitor) {
visitor.visit(this);
}
}
// We have condos
public class Condo implements Residence {
// imagine getters and setters for these values
private double squareFeet;
private boolean hasView;
@Override
public void accept(final ResidenceVisitor visitor) {
visitor.visit(this);
}
}
// This class will calculate the value of our portfolio
interface ResidenceVisitor {
int visit(DetachedHouse detachedHouse);
int visit(Condo condo);
}
// This class will calculate the value of our portfolio
public class CutterModelPortfolioCalculator implements ResidenceVisitor {
// imagine getters and setters for this value
private int portfolioValue;
@Override
public int visit(final DetachedHouse detachedHouse) {
return (detachedHouse.getSquareFeet() * 2,000) + (detachedHouse.getLotSize() * 100);
}
@Override
public int visit(final Condo condo) {
int value = condo.getSquareFeet() * 1,000;
if (portfolioValue.hasView()) {
value += 10,000;
}
return value;
}
}
// an example of how it could be executed
final CutterModelPortfolioCalculator visitor = new CutterModelPortfolioCalculator();
int portfolioValue = 0;
for (final Residence residence : residences) {
portfolioValue += residence.accept(visitor);
}
System.out.println("Total portfolio value: $" + portfolioValue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment