I have two interfaces :
interface IStudent
{
string Name { get; }
string EducationLevel { get; }
}
interface ITeacher
{
string Name { get; }
string Department { get; }
}
How would you design it in C# such that a an object could
Any thought ?
I can do 2 classes implementing directly the two interfaces. But for a person being both a teacher AND a student, I am going to have 2 different objects : I want only one !
I would extract a common interface:
interface IPerson
{
string Name { get; }
}
interface IStudent : IPerson
{
string EducationLevel { get; }
}
interface ITeacher : IPerson
{
string Department { get; }
}
Think about why your two interfaces have the same property. They both have a name, and why do they have a name? Because they're both a person. So there you have your common interface.
Classes implementing both interfaces will only need to implement Name once, because it's part of IPerson.
The following is perfectly legal:
public class LearningTeacher : ITeacher, IStudent
{
public string EducationLevel
{
get { return /*...*/; }
}
public string Department
{
get { return /*...*/; }
}
public string Name
{
get { return /*...*/; }
}
}
The Name property is the implementation of ITeacher.Name and IStudent.Name.
If the implementation of the properties is the same in Student and LearningTeacher you can make LearningTeacher have a Student instance and a Teacher instance internally, making it effectively a decorator. Like this, you wouldn't have to repeat the implementation:
public class LearningTeacher : ITeacher, IStudent
{
Teacher _teacher;
Student _student;
public LearningTeacher(string name, string educationalLevel,
string department)
{
_student = new Student(name, educationalLevel);
_teacher = new Teacher(name, department);
}
public string EducationLevel
{
get { return _student.EducationLevel; }
}
public string Department
{
get { return _teacher.Department; }
}
public string Name
{
get { return _student.Name; }
}
}
This is the only way, because .NET doesn't support multiple inheritance. You can only implement multiple interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With