我正在开发一个应用程序,它建立在另一个开发人员编写的类上(我没有源代码)。
我希望使用该类的所有功能,但也希望使用其他功能对其进行扩展。通常为了实现这一点,我会定义一个接口 ( MyInterface ) 并在实现MyInterface时从我自己的 ( MyClass )扩展外部类 ( TheyClass ) 。
public interface TheirClassInterface {
public void theirMethod1();
public void theirMethod2();
}
public class TheirClass implements TheirClassInterface {
public void theirMethod1() { ... }
public void theirMethod2() { ... }
}
public class TheirOtherClass {
public void theirOtherMethod1(TheirClassInterface o) { ... }
}
public interface MyInterface() {
public void myMethod1();
}
public class MyClass extends TheirClass implements MyInterface {
public void myMethod1() { ... }
}
public class MyNewClass extends MyClass {
public void MyNewClassMethod() { ... }
}
问题因以下事实而变得复杂:
- 我现在希望创建一个新类(MyNewClass ),它为MyClass添加附加功能,但我不希望我的代码依赖于TheyClass。
- 我希望能够将我的类用作TheyOtherClass方法的参数。
为了解决这个问题,我重构了我的代码,改为使用组合而不是继承并实现TheyClassInterface。这可行,但需要我实现许多方法并将它们委托给theirClassObject(实际上,它们的ClassInterface包含大量方法)。
public interface TheirClassInterface {
public void theirMethod1();
public void theirMethod2();
}
public class TheirClass implements TheirClassInterface {
public void theirMethod1() { ... }
public void theirMethod2() { ... }
}
public class TheirOtherClass {
public void theirOtherMethod1(TheirClassInterface o) { ... }
}
public interface MyInterface() {
public void myMethod1();
}
public class MyClass implements TheirClassInterface, MyInterface {
private TheirClass theirClassObject;
public void myMethod1() { ... }
public void theirMethod1() { theirClassObject.theirMethod1(); }
public void theirMethod2() { theirClassObject.theirMethod2(); }
}
public class MyNewClass extends MyClass {
public void MyNewClassMethod() { ... }
}
我的问题是我的方法在这种情况下是否合适,是否可以改进,因为在我看来,我的代码使用过多的委托来完成工作。
非常感谢任何人对此提供的任何指导。
丹尼