using System; using System.Collections;
namespace DoFactory.GangOfFour.Visitor.Structural { // MainApp test application
class MainApp { staticvoid Main() { // Setup structure ObjectStructure o = new ObjectStructure(); o.Attach(new ConcreteElementA()); o.Attach(new ConcreteElementB());
// Create visitor objects ConcreteVisitor1 v1 = new ConcreteVisitor1(); ConcreteVisitor2 v2 = new ConcreteVisitor2();
// Structure accepting visitors o.Accept(v1); o.Accept(v2);
// Wait for user Console.Read(); } }
// "Visitor"
abstractclass Visitor { publicabstractvoid VisitConcreteElementA( ConcreteElementA concreteElementA); publicabstractvoid VisitConcreteElementB( ConcreteElementB concreteElementB); }
// "ConcreteVisitor1"
class ConcreteVisitor1 : Visitor { publicoverridevoid VisitConcreteElementA( ConcreteElementA concreteElementA) { Console.WriteLine("{0} visited by {1}", concreteElementA.GetType().Name, this.GetType().Name); }
publicoverridevoid VisitConcreteElementB( ConcreteElementB concreteElementB) { Console.WriteLine("{0} visited by {1}", concreteElementB.GetType().Name, this.GetType().Name); } }
// "ConcreteVisitor2"
class ConcreteVisitor2 : Visitor { publicoverridevoid VisitConcreteElementA( ConcreteElementA concreteElementA) { Console.WriteLine("{0} visited by {1}", concreteElementA.GetType().Name, this.GetType().Name); }
publicoverridevoid VisitConcreteElementB( ConcreteElementB concreteElementB) { Console.WriteLine("{0} visited by {1}", concreteElementB.GetType().Name, this.GetType().Name); } }
// "Element"
abstractclass Element { publicabstractvoid Accept(Visitor visitor); }
// "ConcreteElementA"
class ConcreteElementA : Element { publicoverridevoid Accept(Visitor visitor) { visitor.VisitConcreteElementA(this); }
publicvoid OperationA() { } }
// "ConcreteElementB"
class ConcreteElementB : Element { publicoverridevoid Accept(Visitor visitor) { visitor.VisitConcreteElementB(this); }
publicvoid OperationB() { } }
// "ObjectStructure"
class ObjectStructure { private ArrayList elements = new ArrayList();
publicvoid Attach(Element element) { elements.Add(element); }
publicvoid Detach(Element element) { elements.Remove(element); }
publicvoid Accept(Visitor visitor) { foreach (Element e in elements) { e.Accept(visitor); } } } }
|