访问者模式

访问者模式, 表示一个作用与某对象结构中的各元素的操作. 它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作.

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
abstract class Visitor {
public abstract void VisitConcreteElementA(ConcreteElementA concreteElementA);
public abstract void VisitConcreteElementB(ConcreteElementB concreteElementB);
}
class ConcreteVisitor1 : Visitor {
public override void VisitConcreteElementA(ConcreteElementA concreteElementA) {
// todo
}
public override void VisitConcreteElementB(ConcreteElementB concreteElementB) {
// todo
}
}
class ConcreteVisitor2 : Visitor {
public override void VisitConcreteElementA(ConcreteElementA concreteElementA) {
// todo
}
public override void VisitConcreteElementB(ConcreteElementB concreteElementB) {
// todo
}
}
abstract class Element {
public abstract void Accept(Visitor visitor);
}
class ConcreteElementA : Element {
public override void Accept(Visitor visitor) {
visitor.VisitConcreteElementA(this);
}
public void OperationA {
// todo
}
}
class ConcreteElementB : Element {
public override void Accept(Visitor visitor) {
visitor.VisitConcreteElementB(this);
}
public void OperationB {
// todo
}
}
class ObjectStructure {
private IList<Element> elements = new List<Element>();
public void Attach(Element element) {
elements.Add(element);
}
public void Detach(Element element) {
elements.Remove(element);
}
public void Accept(Visitor visitor) {
foreach(Element element in elements) {
element.Accept(visitor);
}
}
}
public static void Main(stringp[] agrs) {
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.Attach(new ConcreteElementA());
objectStructure.Attach(new ConcreteElementB());
ConcreteVisitor1 concreteVisitor1 = new ConcreteVisitor1();
ConcreteVisitor2 concreteVisitor2 = new ConcreteVisitor2();
objectStructure.Accept(concreteVisitor1);
objectStructure.Accept(concreteVisitor2);
}