我想知道下面是否可以使用訪問者模式。從Accept()或Visit()調用返回時,我感到有點不舒服 - 這是這種模式的適當用法,如果不是,爲什麼不呢?在C中使用泛型的訪問者模式#
注:長的代碼示例道歉,似乎有必要跨越我在做什麼,以獲得儘可能遊客似乎總是有點棘手...
interface IAnimalElement<T>
{
T Accept(IAnimalVisitor<T> visitor);
}
interface IAnimalVisitor<T>
{
T Visit(Lion lion);
T Visit(Peacock peacock);
T VisitZoo(List<Animal> animals);
}
abstract class Animal
{
public int Age { get; protected set; }
}
class Lion : Animal, IAnimalElement<int>
{
public Lion(int age)
{
Age = age;
}
public int Accept(IAnimalVisitor<int> visitor)
{
return visitor.Visit(this);
}
}
class Peacock : Animal, IAnimalElement<int>
{
public Peacock(int age)
{
Age = age;
}
public int Accept(IAnimalVisitor<int> visitor)
{
return visitor.Visit(this);
}
}
class AnimalAgeVisitor : IAnimalVisitor<int>
{
public int TotalAge { get; private set; }
int IAnimalVisitor<int>.Visit(Lion lion)
{
TotalAge += lion.Age;
return lion.Age;
}
int IAnimalVisitor<int>.Visit(Peacock peacock)
{
TotalAge += peacock.Age + 10;
return peacock.Age + 10; // peacocks ages are always -10y, correct.
}
public int VisitZoo(List<Animal> animals)
{
// Calculate average animal age.
int sum = 0;
int count = 0;
foreach (IAnimalElement<int> animal in animals)
{
sum += animal.Accept(this);
++count;
}
return count == 0 ? 0 : sum/count;
}
}
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>() { new Lion(10),
new Lion(15), new Peacock(3), new Lion(2), new Peacock(9) };
AnimalAgeVisitor visitor = new AnimalAgeVisitor();
Console.WriteLine("Average age = {0}, Total age = {1}",
visitor.VisitZoo(animals), visitor.TotalAge);
}
}
哦,順便說一句,你應該完全使用`[DebuggerStepThrough]``屬性在'Accept'方法上。 – 2014-02-07 09:58:02