基本信息
源码名称:C#设计模式之【访问者模式】
源码大小:0.08M
文件格式:.zip
开发语言:C#
更新时间:2015-09-09
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
using System; using System.Collections.Generic; using System.Text; namespace 访问者模式 { class Program { static void Main(string[] args) { 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); Amativeness v3 = new Amativeness(); o.Display(v3); Marriage v4 = new Marriage(); o.Display(v4); Console.Read(); } } //状态 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); } } //恋爱 class Amativeness : 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 Marriage : 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); } } //人 abstract class Person { //接受 public abstract void Accept(Action visitor); } //男人 class Man : Person { public override void Accept(Action visitor) { visitor.GetManConclusion(this); } } //女人 class Woman : Person { public override void Accept(Action visitor) { visitor.GetWomanConclusion(this); } } //对象结构 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); } } } }