访问者模式
代码
using System;
using System.Collections;
using System.Collections.Generic;
abstract class Action
{
public abstract void GetManConclusion(Man man);
public abstract void GetWomanConclusion(Woman woman);
}
class Success:Action
{
public override void GetManConclusion(Man man)
{
Console.WriteLine("{0}{1}时,背后多半有一个伟大的女人。", man.GetType().Name, this.GetType().Name);
}
public override void GetWomanConclusion(Woman woman)
{
Console.WriteLine("{0}{1}时,背后多半有一个伟大的女人。", woman.GetType().Name, this.GetType().Name);
}
}
abstract class Person
{
public abstract void Accept(Action action);
}
class Woman:Person
{
public override void Accept(Action action)
{
action.GetWomanConclusion(this);
}
}
class Man:Person
{
public override void Accept(Action action)
{
action.GetManConclusion(this);
}
}
class ObjectStructure
{
private IList<Person> elements=new List<Person>();
public void Add(Person element)
{
elements.Add(element);
}
public void Detach(Person element)
{
elements.Remove(element);
}
public void Display(Action voisitor)
{
foreach(Person e in elements)
{
e.Accept(voisitor);
}
}
}
public class MyClass
{
public static void Main()
{
ObjectStructure o=new ObjectStructure();
o.Add(new Man());
Success v1=new Success();
o.Display(v1);
Console.ReadLine();
}
}
using System.Collections;
using System.Collections.Generic;
abstract class Action
{
public abstract void GetManConclusion(Man man);
public abstract void GetWomanConclusion(Woman woman);
}
class Success:Action
{
public override void GetManConclusion(Man man)
{
Console.WriteLine("{0}{1}时,背后多半有一个伟大的女人。", man.GetType().Name, this.GetType().Name);
}
public override void GetWomanConclusion(Woman woman)
{
Console.WriteLine("{0}{1}时,背后多半有一个伟大的女人。", woman.GetType().Name, this.GetType().Name);
}
}
abstract class Person
{
public abstract void Accept(Action action);
}
class Woman:Person
{
public override void Accept(Action action)
{
action.GetWomanConclusion(this);
}
}
class Man:Person
{
public override void Accept(Action action)
{
action.GetManConclusion(this);
}
}
class ObjectStructure
{
private IList<Person> elements=new List<Person>();
public void Add(Person element)
{
elements.Add(element);
}
public void Detach(Person element)
{
elements.Remove(element);
}
public void Display(Action voisitor)
{
foreach(Person e in elements)
{
e.Accept(voisitor);
}
}
}
public class MyClass
{
public static void Main()
{
ObjectStructure o=new ObjectStructure();
o.Add(new Man());
Success v1=new Success();
o.Display(v1);
Console.ReadLine();
}
}