I am trying to understand the benefit of having the visitor pattern within an API. The below example is one I saw and I wanted an example as to why the pattern in beneficial i.e benefits. What would be the alternative implementation that would be negative and why compared to this. What benefit can be gained from the below implementation. In this api it contacts multiple universities to get the courses that they offer. Each get course service then has a defined number of responses using the Visitor Pattern:
Controller
[HttpGet]
public async Task<IActionResult> Get()
{
// CourseService already retrieved for a given uni
var result = await courseService.GetCourses(userSession);
return result.Accept(new CourseVisitor());
}
Service - Each Uni has there own GetCourses Service but they all have set responses due to the Visitor pattern
public async Task<CoursesResult> GetCourses(UserSession userSession) {
// Depending on response from a given uni a set number of responses can be returned across ass uni services e.g
return new CoursesResult.BadRequest(); **or**
return new CoursesResult.Success(); etc
}
Element Abstract / Concrete Element
public abstract class GetCourses
{
public abstract T Accept<T>(ICourseVisitor<T> visitor);
public class Successful : CoursesResult
{
public CourseList Response { get; }
public Successful(CourseList response)
{
Response = response;
}
public override T Accept<T>(ICourseVisitor<T> visitor)
{
return visitor.Visit(this);
}
}
// Other responses then defined e.g Bad Request
IVisitor
public interface ICourseVisitor<out T>
{
T Visit(GetCoursesResult.Successful result);
T Visit(GetCoursesResult.BadRequest result);
Visitor
internal class CourseVisitor : ICourseVisitor<IActionResult>
{
public IActionResult Visit(GetCourses.Successful result)
{
return new OkObjectResult(result.Response);
}
Aucun commentaire:
Enregistrer un commentaire