gst*_*low 8 java inheritance implementation interface composition
最近我接受了一次采访,我被问到以下问题.给定以下类/接口结构:

题:
如何实现接口EmployedStudent来重用代码StudentImpl和EmployeeImpl.
我建议将员工和学生组成我的实施.
根据采访者的反应,我不认为他们认为这是最好的解决方案.我花了很多时间思考它,但我无法想出另一个解决方案.
创建一个实现两者Employee和的类Student.在您的班级中,创建两个EmployeeImpl和的实例StudentImpl.使您的类将所有方法调用委托给其中一个对象.
public class EmployedStudent implements Employee, Student {
private EmployeeImpl employee = new EmployeeImpl();
private StudentImpl student = new StudentImpl();
public int getSalary() {
return this.employee.getSalary();
}
public float getAverageGrade() {
return this.student.getAverageGrade();
}
}
Run Code Online (Sandbox Code Playgroud)
由于java不支持多重继承,你可以/应该
然后,这些字段由相应方法的“我们的”实现引用。
这是来自GoF的设计模式之一,我认为是Proxy模式。