设计模式:访问者模式(Visitor)
定 义:表示作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
结构图:
示例:
、
状态类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//状态的抽象类 abstract class Action { public abstract void GetManConclusion(Man concreteElementA); //得到男人的结论或反应 public abstract void GetWomanConclusion(Woman concreteElementB); //得到女人的结论或反应 } //成功 状态 class Success : Action { public override void GetManConclusion(Man concreteElementA) { Console.WriteLine("{0}{1}时,多半有个伟大的女人", concreteElementA.GetType().Name, this.GetType().Name); } public override void GetWomanConclusion(Woman concreteElementB) { Console.WriteLine("{0}{1}时,肯定有个不成功的男人", concreteElementB.GetType().Name, this.GetType().Name); } } //失败 状态 class Failing : Action { public override void GetManConclusion(Man concreteElementA) { Console.WriteLine("{0}{1}时,闷头喝酒,谁也不用劝", concreteElementA.GetType().Name, this.GetType().Name); } public override void GetWomanConclusion(Woman concreteElementB) { Console.WriteLine("{0}{1}时,眼泪汪汪,谁也劝不了", concreteElementB.GetType().Name, this.GetType().Name); } }
人,男人,女人:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//"人"的抽象类 abstract class Person1 { public abstract void Accept(Action visitor); //接受,用来获得状态对象 } //男人 class Man : Person1 { public override void Accept(Action visitor) { visitor.GetManConclusion(this); } } //女人 class Woman : Person1 { public override void Accept(Action visitor) { visitor.GetWomanConclusion(this); } }
对象结构类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//对象结构 class ObjectStructure { public IList<Person1> persons = new List<Person1>(); //增加 public void Attach(Person1 person) { persons.Add(person); } //移除 public void Detach(Person1 person) { persons.Remove(person); } //查看显示 public void Display(Action visitor) { foreach (Person1 person in persons) { person.Accept(visitor); } } }
客户端调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ObjectStructure o = new ObjectStructure(); //对象结构中加入要对比的“男人”和“女人” o.Attach(new Man()); o.Attach(new Woman()); //成功时的反应 Success v1 = new Success(); o.Display(v1); //失败时的时的反应 Failing v2 = new Failing(); o.Display(v2); //结婚时的反应 //Marry v3 = new Marry(); //o.Display(v3);
结果: