i am trying to programm a Turtle programm in Java following the Visitor pattern. therefore i have the Visitor:
public interface Visitor {
void visit(Go go);
void visit(Turn turn);
void visit(Call call);
void visit(PenDown pendown);
void visit(PenUp penup);
void visit(Repeat repeat);
void visit(Sequence sequence);
void visit(Subroutine subroutine);
}
and the Abstract Visitor which should implement some of the visit methods:
public abstract class AbstractVisitor implements Visitor {
protected Turtle turtle;
protected AbstractVisitor(Turtle turtle){
this.turtle = turtle;
}
public AbstractVisitor() {
}
public void visit(Turn turn){
turtle.turn(turn.w);
}
public void visit(Sequence sequence){
}
public void visit(Repeat repeat) {
int d = repeat.rep;
for(int i = 0; i<repeat.rep; i++){
for(int s = 0; s<repeat.d.size(); s++){
}
}
}
public void visit(Subroutine subroutine) {
}
public void visit(Call call) {
}
public void visit(PenDown penDown) {
}
public void visit(PenUp penUp) {
}
}
i am Trying to implement the visit(Repeat repeat)
public class Repeat implements Stmt {
public int rep;
public List<Object> d;
public Repeat(int i,Stmt ... s1) {
this.rep = i;
for (int q = 0; q < s1.length; q++) {
d.add( s1[q]);
}
}
@Override
public void accept(Visitor v) {
{
v.visit(this);
}
}
}
this method should get an integer i and some other classes which also implements the Interface Stmt
public interface Stmt {
void accept(Visitor v);
}
like the Class Go
public class Go implements Stmt {
public double dist;
public Go(double d){
if(d<0 ) {
throw new IllegalArgumentException("Die Strecke muss positiv sein");
} this.dist = d;
}
public void accept(Visitor v) {
}
}
So You should be able to hand over an Integer i and as many Classes like Go. the repeat class should do the visit method for each class handed over and repeat it i times.
Now my Question is how can I check which Class is in the Array of Stmt's I hand over to Repeat? Or is it Wrong how I did the parameters in Repeat?
As a example i want to be able to call PROG1.accept(visitor)
with public static final Stmt PROG1 = new Repeat(4, new Go(50), new Turn(90));
I didn't understand completely your problem! But if your question is :
You have an Interface
and you have two classes implementing this interface each them has a different body for the accept method
and
and your question as I understand it is: HOW do I know which body will be used if I call the accept() method ! is the accept() from X class or the accept() from the Y class ??
Answer : it depends on your main application, as you know you cannot instantiate an interface! so it depends on which class you have instantiated! you will have for example :
for this one var.accept() will call the body from the X class!