Created
April 25, 2015 20:50
-
-
Save mickeypash/05f0f69841a333e132b4 to your computer and use it in GitHub Desktop.
Visitor pattern AP 2015 Simon's example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MyElement only implements the accept method and this just called the visit method of MyVisitor | |
public interface MyElement { | |
public void accept(MyVisitor visitor); | |
} | |
import java.util.Calendar; | |
public class Human implements MyElement { | |
public Calendar dOB; | |
public Human(Calendar d) { | |
dOB = d; | |
} | |
public void accept(MyVisitor visitor) { | |
visitor.visit(this); | |
} | |
} | |
public class Dog implements MyElement { | |
public Integer ageYears; | |
public Dog(Integer a) { | |
ageYears = a; | |
} | |
public void accept(MyVisitor visitor) { | |
visitor.visit(this); | |
} | |
} | |
// MyVisitor forces subclasses to implement methods for each of the original objects | |
public interface MyVisitor { | |
public void visit(Dog dog); | |
public void visit(Human human); | |
} | |
import java.util.GregorianCalendar; | |
public class CompAgeDaysVisitor implements MyVisitor { | |
public void visit(Human human) { | |
// Converting dates to differences in days | |
GregorianCalendar today = new GregorianCalendar(); | |
long diffSeconds = (today.getTimeInMillis()) - human.dOB.getTimeInMillis())/1000; | |
Integer ageDays = (int) diffSeconds/(60*60*24); | |
System.out.println("This human is " + ageDays + " days old."); | |
} | |
public void visit(Dog dog) { | |
Integer ageDays = dog.ageYears * 365; | |
System.out.println("This dog is " + ageDays + " days old."); | |
} | |
} | |
import java.util.*; | |
public class TestVisitor { | |
public static void main(String[] args) { | |
// set the age of the dog in years | |
Dog d = new Dog(5); | |
// set the age of the human as dOB from the Greg cal | |
Calendar cal = new GregorianCalendar(); | |
cal.set(1995,5,12); | |
Human h = new Human(cal); | |
CompAgeDaysVisitor c = new CompAgeDaysVisitor(); | |
d.accept(c); | |
h.accept(c); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment