-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisitorExample.java
More file actions
55 lines (44 loc) · 1.38 KB
/
Copy pathVisitorExample.java
File metadata and controls
55 lines (44 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.ArrayList;
import java.util.List;
public class VisitorExample {
public static void main(String[] args) {
List<Element> elements = new ArrayList<>();
elements.add(new ConcreteElementA());
elements.add(new ConcreteElementB());
Visitor visitor = new ConcreteVisitor();
for (Element element : elements) {
element.accept(visitor);
}
}
interface Element {
void accept(Visitor visitor);
}
static class ConcreteElementA implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String operationA() {
return "ConcreteElementA";
}
}
static class ConcreteElementB implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String operationB() {
return "ConcreteElementB";
}
}
interface Visitor {
void visit(ConcreteElementA element);
void visit(ConcreteElementB element);
}
static class ConcreteVisitor implements Visitor {
public void visit(ConcreteElementA element) {
System.out.println("Visited " + element.operationA());
}
public void visit(ConcreteElementB element) {
System.out.println("Visited " + element.operationB());
}
}
}