File tree Expand file tree Collapse file tree
DesignPatterns/VisitorPattern/VisitorPattern Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff line change 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" />
You can’t perform that action at this time.
0 commit comments