-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDS23_Visitor_2.java
More file actions
99 lines (74 loc) · 2.24 KB
/
DS23_Visitor_2.java
File metadata and controls
99 lines (74 loc) · 2.24 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
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
96
97
98
//Visitor
//不是很理解这个有问题
import java.util.*;
interface Visitor {
public void visitString(StringElement stringE);
public void visitFloat(FloatElement floatE);
public void visitCollection(Collection collection);
}
//ConcreteVisitor
class ConcreteVisitor implements Visitor {
public void visitCollection(Collection collection) {
// TODO Auto-generated method stub
Iterator iterator = (Iterator)collection.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Visitable) {
((Visitable)o).accept(this);
}
}
}
public void visitFloat(FloatElement floatE) {
System.out.println(floatE.getFe());
}
public void visitString(StringElement stringE) {
System.out.println(stringE.getSe());
}
}
//Element
interface Visitable {
public void accept(Visitor visitor);
}
//ConcreteElement
class FloatElement implements Visitable {
private Float fe;
public FloatElement(Float fe) {
this.fe = fe;
}
public Float getFe() {
return this.fe;
}
public void accept(Visitor visitor) {
visitor.visitFloat(this);
}
}
class StringElement implements Visitable {
private String se;
public StringElement(String se) {
this.se = se;
}
public String getSe() {
return this.se;
}
public void accept(Visitor visitor) {
visitor.visitString(this);
}
}
public class DS23_Visitor{
public static void main(String[] args) {
Visitor visitor = new ConcreteVisitor();
StringElement se = new StringElement("abc");
se.accept(visitor);
FloatElement fe = new FloatElement(new Float(1.5));
fe.accept(visitor);
System.out.println("===========");
List result = new ArrayList();
result.add(new StringElement("abc"));
result.add(new StringElement("abc"));
result.add(new StringElement("abc"));
//result.add(new FloatElement(new Float(1.5)));
// result.add(new FloatElement(new Float(1.5)));
//result.add(new FloatElement(new Float(1.5)));
visitor.visitCollection(result);
}
}