结构 | |
意图 | 表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。 |
适用性 |
|
1 using System; 2 3 abstract class Visitor 4 { 5 abstract public void VisitElementA(ConcreteElementA a); 6 abstract public void VisitElementB(ConcreteElementB b); 7 } 8 9 class ConcreteVisitor1 : Visitor 10 { 11 override public void VisitElementA(ConcreteElementA a) 12 { 13 14 } 15 16 override public void VisitElementB(ConcreteElementB b) 17 { 18 19 } 20 } 21 22 abstract class Element 23 { 24 abstract public void Accept(Visitor v); 25 } 26 27 class ConcreteElementA : Element 28 { 29 public Visitor myVisitor; 30 override public void Accept(Visitor v) 31 { 32 myVisitor = v; 33 } 34 35 public void OperationA() 36 { 37 38 } 39 40 public void DoSomeWork() 41 { 42 // do some work here 43 // . . . 44 45 // Get visitor to visit 46 myVisitor.VisitElementA(this); 47 48 // do some more work here 49 // . . . 50 } 51 } 52 53 class ConcreteElementB : Element 54 { 55 override public void Accept(Visitor v) 56 { 57 58 } 59 60 public void OperationB() 61 { 62 63 } 64 } 65 66 /// <summary> 67 /// Summary description for Client. 68 /// </summary> 69 public class Client 70 { 71 public static int Main(string[] args) 72 { 73 ConcreteElementA eA = new ConcreteElementA(); 74 ConcreteElementB eB = new ConcreteElementB(); 75 ConcreteVisitor1 v1 = new ConcreteVisitor1(); 76 77 eA.Accept(v1); 78 eA.DoSomeWork(); 79 80 return 0; 81 } 82 }
访问者模式
时间: 2024-10-23 16:35:30