文章目录
  1. 访问者模式

访问者模式

  • 表示一个作用于某对象结构中各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
    Visitor
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
99
100
101
102
103
104
105
public interface Visitor {
void visit(CPU cpu);
void visit(EarPhone earPhone);
}
public class GeneralVisitor implements Visitor{
@Override
public void visit(CPU cpu) {
System.out.println("CPU名称:"+cpu.getModelName());
}
@Override
public void visit(EarPhone earPhone) {
System.out.println("耳机名称:"+earPhone.getInterfaceName());
}
}
public class ProVisitor implements Visitor{
@Override
public void visit(CPU cpu) {
System.out.println("CPU:"+cpu.getModelName()+" "+cpu.getHz());
}
@Override
public void visit(EarPhone earPhone) {
System.out.println("耳机:"+earPhone.getInterfaceName()+" "+earPhone.getPrice());
}
}
public interface Component {
void accept(Visitor visitor);
}
public class CPU implements Component {
private int hz;
private String modelName;
public int getHz() {
return hz;
}
public void setHz(int hz) {
this.hz = hz;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public class EarPhone implements Component {
private String interfaceName;
private int price;
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public class Phone implements Component {
private List<Component> components;
public List<Component> getComponents() {
return components;
}
public void setComponents(List<Component> components) {
this.components = components;
}
public void accept(Visitor visitor) {
for(Component component:components){
component.accept(visitor);
}
}
}
文章目录
  1. 访问者模式