visitor-theory-reflection.cs

  using System;
  using System.Reflection;
  using ObjectStructure;

  // Visitor Pattern - Example    Judith Bishop October 2007
  // Sets up an object structure and visits it
  // in two ways - for counting using reflection
   
  namespace ObjectStructure {

    class Element {
      public Element Next {get; set;}
      public Element Part {get; set;}
      public Element () {}
      public Element (Element next) {
        Next = next;
      }
    }
 
    class ElementWithLink : Element {
      public ElementWithLink (Element part, Element next) {
        Next = next;
        Part = part;
      }
    }
  }
 
  abstract class IVisitor {
    public void ReflectiveVisit(Element element) {
       // Use reflection to find and invoke the correct Visit method
       Type[] types = new Type[] {element.GetType()};
       MethodInfo methodInfo = this.GetType().GetMethod("Visit", types);
       if (methodInfo != null)
                methodInfo.Invoke(this, new object[] {element});
      else Console.WriteLine("Unexpected Visit");
      }
  }

   // Visitor
  class CountVisitor : IVisitor {
      public int Count {get; set;}
      public void CountElements(Element element) {
        ReflectiveVisit(element);
        if (element.Part!=null) CountElements(element.Part);
        if (element.Next!=null) CountElements(element.Next);
      }
     
     public void Visit(ElementWithLink element) {
       Console.WriteLine("Not counting");
     }
     // Only Elements are counted
     public void Visit(Element element) {
           Count++;
     }
  }

  // Client
  class Client {
    
  static void Main() {
    // Set up the object structure
    Element objectStructure =
      new Element(
          new Element(
          new ElementWithLink(
           new Element(           
                 new Element(  
                   new ElementWithLink(
               new Element(null),        
                 new Element(
                 null)))),
      new Element(
          new Element(
          new Element(null))))));

    Console.WriteLine ("Count the elements");
    CountVisitor visitor = new CountVisitor();
    visitor.CountElements(objectStructure);
    Console.WriteLine("Number of Elements is: "+visitor.Count);
  }
}
/*
Count the elements
Not counting
Not counting
Number of Elements is: 9
*/

转载于:https://www.cnblogs.com/shihao/archive/2012/05/11/2495988.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值