创建抽象访问者接口
public interface Person {
void Feed(Cat cat);
void Feed(Dog dog);
}
//主人
public class Owner : Person
{
public void Feed(Cat cat)
{
Console.WriteLine("主人喂食猫");
}
public void Feed(Dog dog)
{
Console.WriteLine("主人喂食狗");
}
}
//其他人
public class Someone : Person
{
public void Feed(Cat cat)
{
Console.WriteLine("其他人喂食猫");
}
public void Feed(Dog dog)
{
Console.WriteLine("其他人喂食狗");
}
}
public interface IAnimal {
void Accept(Person person);
}
定义实现 Animal 接口的 具体节点(元素)
public class Dog:IAnimal
{
public void Accept(Person person)
{
person.Feed(this);
Console.WriteLine("好吃!汪汪汪");
}
}
public class Cat:IAnimal
{
public void Accept(Person person)
{
person.Feed(this);
Console.WriteLine("好吃!喵喵喵");
}
}
public class Home
{
private readonly List _nodeList = new List();
public void Action(Person person)
{
foreach (var node in _nodeList)
{
node.Accept(person);
}
}
//添加操作
public void Add(IAnimal animal)
{
_nodeList.Add(animal);
}
}
测试类
class MyClass
{
public static void Main(string[] args)
{
Home home = new Home();
home.Add(new Dog());
home.Add(new Cat());
Owner owner = new Owner();
home.Action(owner);
Someone someone = new Someone();
home.Action(someone);
}
}
运行结果!