lundi 25 mai 2015

Visitor Pattern for two arguments

Here is a problem statement: We have interfaces/super classes Student and Teacher

Student has two implementations/sub clasees, ScienceStudent and PhysicalEducationStudent

Teacher has ScienceTeacher and PhysicalEducationTeacher.

We want to implement a method getMeetingPoint(Student s, Teacher t) which returns a place where they meet based on the type of Student and Teacher.

For example, if its a ScienceStudent and ScienceTeacher they meet at Lab if PEStudent and PETeacher they meet on the Ground and if its a ScienceStudent and PETeacher or vice versa, they meet at cafeteria

We can write a naive method, which checks using instanceof. But the problem is, this becomes complex when Teacher or Student gets extended, and tough to maintain. something like this:

public class MeetingPointDecider {

    getMeetingPoint(Student s,Teacher t) {
        if(s instanceof ScienceStudent && t instanceof ScienceTeacher) {
            return "Lab";
        } else if (s instanceof PhysicalEducationTeacher && t instanceof PhysicalEducationTeacher) {
            return "GRound";
        }
        .
        .
        .
    }
}

Another option is writing a factory, which accepts a Student and a Teacher and returns something like MeetingPointDecision [Ground or Lab], but the problem persists. Is there any good pattern we can use, where we do not have to modify existing classes (or minimal modification) when a new class is added, Say instanceof ScienceStudent we have ChemistryStudent, PhysicsStudent and ChemistryLab, PhysicsLab. There is also a chance of adding more actions, which differs in implementation based on the Student and Teacher type ( Where Visitor is an option, but not sure how to implement with two deciding classes)

Can someone please suggest a good way to implement this?

Thanks!

Aucun commentaire:

Enregistrer un commentaire