设计模式(二十四)——访问者模式

来源:互联网 发布:网络大专多少钱一年 编辑:程序博客网 时间:2024/06/07 14:05

访问者模式(Visitor)

访问者模式,表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。


代码

1.代码如下:

抽象人类

using System;namespace Visitor{//抽象人类public abstract class Person{//接受public abstract void Accept(Action visitor);}}

男人

using System;namespace Visitor{//男人public class Man:Person{public override void Accept (Action visitor){visitor.GetManConclusion (this);}}}

女人

using System;namespace Visitor{//女人public class Woman:Person{public override void Accept (Action visitor){visitor.GetWomanConclusion (this);}}}

状态抽象类

using System;namespace Visitor{//状态抽象类public abstract class Action{//得到男人结论或反应public abstract void GetManConclusion(Person concreteElementA);//得到女人结论或反应public abstract void GetWomanConclusion(Person concreteElementA);}}

成功状态类

using System;namespace Visitor{//成功状态类public class Success:Action{public override void GetManConclusion (Person concreteElementA){Console.WriteLine ("{0}{1}时,背后多半有一个伟大的女人。", concreteElementA.GetType ().Name, this.GetType ().Name);}public override void GetWomanConclusion (Person concreteElementA){Console.WriteLine ("{0}{1}时,背后大多有一个不成功的男人。", concreteElementA.GetType ().Name, this.GetType ().Name);}}}

失败状态类

using System;namespace Visitor{//失败状态类public class Failing:Action{public override void GetManConclusion (Person concreteElementA){Console.WriteLine ("{0}{1}时,闷头喝酒,谁也不用劝。", concreteElementA.GetType ().Name, this.GetType ().Name);}public override void GetWomanConclusion (Person concreteElementA){Console.WriteLine ("{0}{1}时,眼泪汪汪,谁也劝不了。", concreteElementA.GetType ().Name, this.GetType ().Name);}}}

对象结构

using System;using System.Collections.Generic;namespace Visitor{//对象结构public class ObjectStructure{private IList<Person> elements=new List<Person>();//增加public void Attach(Person element){elements.Add (element);}//移除public void Detach(Person element){elements.Remove (element);}//查看显示public void Display(Action visitor){foreach (Person e in elements) {e.Accept (visitor);}}}}
2.客户端代码如下:

客户端

using System;namespace Visitor{class MainClass{public static void Main (string[] args){ObjectStructure objectStructure = new ObjectStructure ();objectStructure.Attach (new Man ());objectStructure.Attach (new Woman ());//成功时的反应Success v1=new Success();objectStructure.Display (v1);//失败时的反应Failing v2=new Failing();objectStructure.Display (v2);}}}
3.运行结果

UML图


源码下载地址:https://gitee.com/ZhaoYongshuang/DesignPattern.git
阅读全文
1 0
原创粉丝点击