Let's consider an example wherein I have to model the following:
- Class to schedule exams for a Student, lets call it
StudentExamScheduler - Class to schedule exam for a Class. Let's call it
ClassExamSchedulerand currently it depends on the logic provided byStudentExamScheduler.
So since both the classes schedule exams, I created an interface ExamScheduler which both the classes would implement. Reason being:
- They are essentially scheduling exams
- would give me the flexibility to swap the schedulers in-and-out as functionality changes.
This is how the interface would look:
interface ExamScheduler {
scheduleExam(data);
}
Now each of my concrete class implements this interface and ClassExamScheduler now uses the StudentExamScheduler to delegate some responsibilities.
class ClassExamScheduler implements ExamScheduler {
private ExamScheduler studentExamScheduler;
public scheduleExam() {
studentExamScheduler.scheduleExam();
// do other stuff
}
}
Is this a valid use of Interface & Composition? Typically I have seen Interface being used for polymorphism. But in this use case I use it to provide me flexibility to inject new classes when the requirements change.