将数据结构与数据操作分离, 用于稳定的数据结构和易变的操作耦合问题
访问者模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| abstract class Visitor { public abstract void VisitorConcreateElementA(ConcreateElementA concreateElementA); public abstract void VisitorConcreateElementB(ConcreateElementB concreateElementB); } class ConcreateVisitor1 : Visitor { public override void VisitorConcreateElementA(ConcreateElementA concreateElementA) { Console.WriteLine("{0}被{1}访问", ConcreateElementA.GetType().Name, this.GetType().Name); } public override void VisitorConcreateElementB(ConcreateElementB concreateElementB) { Console.WriteLine("{0}被{1}访问", ConcreateElementB.GetType().Name, this.GetType().Name); } } class ConcreateVisitor2 : Visitor { } abstract class Element { public abstract void Accept(Visitor visitor); } class ConcreateElementA : Element { public override void Accept(Visitor visitor) { visitor.VisitConcreateElementA(this); } public void OperationA() {} } class ConcreateElementB : Element { public override void Accept(Visitor visitor) { visitor.VisitConcreateElementB(this); } public void OperationB() {} } class ObjectStructure { private IList<Element> elements = new List<Element>(); public void Attach(Element element) { elements.Add(element); } public void Detach(Element element) { elements.Remove(element); } public void Accept(Visitor visitor) { elements.Foreach(e => e.Accept(visitor)); } }
ObjectStructure o = new ObjectStructure(); o.Attach(new ConcreateElementA); o.Attach(new ConcreateElementB); ConcreateVisitor1 v1 = new ConcreateVisitor1(); ConcreateVisitor1 v2 = new ConcreateVisitor2(); o.Accept(v1); o.Accept(v2);
|