使用这两种技术有什么显着的好处吗?如果有变化,我的意思是访问者模式:http ://en.wikipedia.org/wiki/Visitor_pattern
而下面是一个使用delegate达到同样效果的例子(至少我觉得是一样的)
假设有一组嵌套元素:学校包含包含学生的部门
与其使用访问者模式对每个集合项执行某些操作,不如使用简单的回调(C# 中的操作委托)
说这样的话
class Department
{
List Students;
}
class School
{
List Departments;
VisitStudents(Action<Student> actionDelegate)
{
foreach(var dep in this.Departments)
{
foreach(var stu in dep.Students)
{
actionDelegate(stu);
}
}
}
}
School A = new School();
...//populate collections
A.Visit((student)=> { ...Do Something with student... });
*编辑示例,代表接受多个参数
假设我想通过学生和部门,我可以像这样修改动作定义:动作
class School
{
List Departments;
VisitStudents(Action<Student, Department> actionDelegate, Action<Department> d2)
{
foreach(var dep in this.Departments)
{
d2(dep); //This performs a different process.
//Using Visitor pattern would avoid having to keep adding new delegates.
//This looks like the main benefit so far
foreach(var stu in dep.Students)
{
actionDelegate(stu, dep);
}
}
}
}