get*_*tit 5 c# delegates design-patterns visitor-pattern
使用这两种技术有什么显着的好处吗?如果有变化,我的意思是访客模式:http://en.wikipedia.org/wiki/Visitor_pattern
以下是使用委托实现相同效果的示例(至少我认为它是相同的)
假设有一组嵌套元素:学校包含包含学生的部门
而不是使用访问者模式在每个集合项上执行某些操作,为什么不使用简单的回调(C#中的Action委托)
说这样的话
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... });
Run Code Online (Sandbox Code Playgroud)
*编辑示例,委托接受多个参数
假设我想通过学生和部门,我可以像这样修改动作定义:动作
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
访问者模式通常在有多种访问类型时使用.您只有一种类型Student,因此您不需要访问者模式,只需传入委托实例即可.
假设你想要访问Departments和Students.然后你的访客看起来像这样:
interface ISchoolVisitor
{
void Visit(Department department);
void Visit(Student student);
}
Run Code Online (Sandbox Code Playgroud)
当然,您也可以在这里使用委托,但传递多个委托实例会很麻烦 - 特别是如果您有两种以上的访问类型.