-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisitor.java
95 lines (72 loc) · 1.9 KB
/
visitor.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.util.ArrayList;
import java.util.List;
interface Visitor {
void visitConcreteElementA(ConcreteElementA a);
void visitConcreteElementB(ConcreteElementB b);
}
class ConcreteVisitor1 implements Visitor {
@Override
public void visitConcreteElementA(ConcreteElementA a) {
System.out.println("concrete visitor 1 visit a");
}
@Override
public void visitConcreteElementB(ConcreteElementB b) {
System.out.println("concrete visitor 1 visit b");
}
}
class ConcreteVisitor2 implements Visitor {
@Override
public void visitConcreteElementA(ConcreteElementA a) {
System.out.println("concrete visitor 2 visit a");
}
@Override
public void visitConcreteElementB(ConcreteElementB b) {
System.out.println("concrete visitor 2 visit b");
}
}
interface Element {
void accept(Visitor visitor);
}
class ConcreteElementA implements Element{
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementA(this);
}
void operationA(){
}
}
class ConcreteElementB implements Element {
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementB(this);
}
void operationB(){
}
}
class ObjectStructure {
private List<Element> list = new ArrayList<>();
void add(Element e){
list.add(e);
}
void remove(Element e){
list.remove(e);
}
void accept(Visitor visitor){
for(Element e : list){
e.accept(visitor);
}
}
}
public class Main {
public static void main(String[] args){
ObjectStructure o = new ObjectStructure();
Element e1 = new ConcreteElementA();
Element e2 = new ConcreteElementB();
o.add(e1);
o.add(e2);
Visitor v1 = new ConcreteVisitor1();
Visitor v2 = new ConcreteVisitor2();
o.accept(v1);
o.accept(v2);
}
}