Обычно делают так:
package org.ovk.javalearning;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Structure s = new Structure();
s.visit();
}
}
class Visitor {
void visit(IntElement element) {
System.out.println("int: " + element.value);
}
void visit(StringElement element) {
System.out.println("string: " + element.value);
}
}
interface GenericElement {
void accept(Visitor visitor);
}
class IntElement implements GenericElement {
public int value = 0;
IntElement(int value) {
this.value = value;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class StringElement implements GenericElement {
public String value = "";
StringElement(String value) {
this.value = value;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Structure {
ArrayList<GenericElement> elements;
Structure() {
elements = new ArrayList<GenericElement>();
elements.add(new IntElement(10));
elements.add(new StringElement("Hello!"));
}
void visit() {
Visitor visitor = new Visitor();
for(GenericElement element : elements) {
element.accept(visitor);
}
}
}
А почему не делают так?
package org.ovk.javalearning;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Structure s = new Structure();
s.visit();
}
}
interface GenericElement {
}
class IntElement implements GenericElement {
public int value = 0;
IntElement(int value) {
this.value = value;
}
}
class StringElement implements GenericElement {
public String value = "";
StringElement(String value) {
this.value = value;
}
}
class Structure {
ArrayList<GenericElement> elements;
Structure() {
elements = new ArrayList<GenericElement>();
elements.add(new IntElement(10));
elements.add(new StringElement("Hello!"));
}
void visit() {
for(GenericElement element: elements) {
if(element instanceof IntElement)
System.out.println("int: " + ((IntElement) element).value);
else if (element instanceof StringElement)
System.out.println("string: " + ((StringElement) element).value);
}
}
}