首页 > 解决方案 > turtle programm Java, handing over variety of classes as a parameter and check which class it is

问题描述

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));

标签: java

解决方案


我没有完全理解你的问题!但是,如果您的问题是:

你有一个接口

public interface Stmt {
  void accept(Visitor v);
  }

并且您有两个实现此接口的类,每个类都有不同的 accept 方法主体

public class X implements Stmt{

 public void accept(Visitor v) {
   //code
 }

}

public class Y implements Stmt{

 public void accept(Visitor v) {
   //code
 }}

据我了解,您的问题是:如果我调用 accept() 方法,我怎么知道将使用哪个主体!是 X 类的 accept() 还是 Y 类的 accept() ?

答:这取决于您的主应用程序,因为您知道您无法实例化接口!所以这取决于你实例化了哪个类!例如,您将拥有:

Stmt var = new X();

因为这个 var.accept() 将从 X 类中调用主体!


推荐阅读