定义:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
namespace Visitor
{
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);
Console.Read();
}
}
}
namespace Visitor
{
abstract class Action
{
// 得到男人结论或反应
public abstract void GetManConclusion(Man concreteElementA);
// 得到女人结论或反应
public abstract void GetWomanConclusion(Woman concreteElementB);
}
/// <summary>
///
/// </summary>
abstract class Person
{
// 接受
public abstract void Accept(Action visitor);
}
}
namespace 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);
}
}
}
namespace Visitor
{
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);
}
}
}
namespace Visitor
{
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);
}
}
}
}