设计模式---访问者模式(应该是最后一篇了)

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
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
abstract class Element
{
public abstract void Accept(Visitor v);
}

class Elem1 : Element
{
public override void Accept(Visitor v)
{
v.VisitElem1(this);
}
}

class Elem2 : Element
{
public override void Accept(Visitor v)
{
v.VisitElem2(this);
}
}

abstract class Visitor
{
public abstract void VisitElem1(Elem1 e1);
public abstract void VisitElem2(Elem2 e2);
}

class Visitor1 : Visitor
{
public override void VisitElem1(Elem1 e1)
{
Console.WriteLine(this.GetType().Name + "  " + e1.GetType().Name);
}

public override void VisitElem2(Elem2 e2)
{
Console.WriteLine(this.GetType().Name + "  " + e2.GetType().Name);
}
}

class Visitor2 : Visitor
{
public override void VisitElem1(Elem1 e1)
{
Console.WriteLine(this.GetType().Name + "  " + e1.GetType().Name);
}

public override void VisitElem2(Elem2 e2)
{
Console.WriteLine(this.GetType().Name + "  " + e2.GetType().Name);
}
}

class ObjStructure
{
private List<Element> elems = new List<Element>();

public void add(Element e)
{
elems.Add(e);
}

public void visit(Visitor v)
{
foreach (Element e in elems)
{
e.Accept(v);
}
}
}

class Client
{
public static void Main()
{
ObjStructure o = new ObjStructure();
o.add(new Elem1());
o.add(new Elem2());
o.visit(new Visitor1());
o.visit(new Visitor2());
Console.Read();
}
}
}