Skip to content

Commit 1e24faf

Browse files
committed
访问者模式
1 parent 22c74da commit 1e24faf

4 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace VisitorPattern
8+
{
9+
/// <summary>
10+
/// 结构对象类,结构对象可以认为是一个对访问进行控制的管理者
11+
/// </summary>
12+
class ObjectStructure
13+
{
14+
private List<Element> elements = new List<Element>();
15+
16+
public void Attach(Element element)
17+
{
18+
elements.Add(element);
19+
}
20+
21+
public void Detch(Element element)
22+
{
23+
elements.Remove(element);
24+
}
25+
26+
public void Accept(Visitor visitor)
27+
{
28+
foreach (var element in elements)
29+
{
30+
element.Accept(visitor);
31+
}
32+
}
33+
}
34+
}

DesignPatterns/VisitorPattern/VisitorPattern/Program.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ class Program
1010
{
1111
static void Main(string[] args)
1212
{
13+
14+
ObjectStructure obj = new ObjectStructure();
15+
obj.Attach(new ConcreteElementA());
16+
obj.Attach(new ConcreteElementB());
17+
ConcreteVisitor visitor = new ConcreteVisitor();
18+
obj.Accept(visitor);
1319
}
1420
}
1521
}

DesignPatterns/VisitorPattern/VisitorPattern/Visitor.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,17 @@ abstract class Visitor
1414
public abstract void VisitConcreteElementA(ConcreteElementA element);
1515
public abstract void VisitConcreteElementB(ConcreteElementB element);
1616
}
17+
18+
class ConcreteVisitor : Visitor
19+
{
20+
public override void VisitConcreteElementA(ConcreteElementA element)
21+
{
22+
Console.WriteLine("元素A被访问者访问");
23+
}
24+
25+
public override void VisitConcreteElementB(ConcreteElementB element)
26+
{
27+
Console.WriteLine("元素B被访问者访问");
28+
}
29+
}
1730
}

DesignPatterns/VisitorPattern/VisitorPattern/VisitorPattern.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
</ItemGroup>
4444
<ItemGroup>
4545
<Compile Include="Element.cs" />
46+
<Compile Include="ObjectStructure.cs" />
4647
<Compile Include="Program.cs" />
4748
<Compile Include="Properties\AssemblyInfo.cs" />
4849
<Compile Include="Visitor.cs" />

0 commit comments

Comments
 (0)