我有一个无法更改的现有框架,它读取 2 个属性
ClassA=somepackage.AnImplementationOfInterfaceAClassB=somepackage.AnImplementationOfInterfaceB
它按顺序调用public methodAa new ClassA(), public methodBon anew ClassB()
我想做一个class C实现接口 A、B 并提供钩子methodC1,methodC2用于class D覆盖(methodA&methodB包含很多样板和复杂的实现 - methodC1&methodC2将封装业务逻辑)。那么我的属性将是
ClassA=somepackage.classDClassB=somepackage.classD
问题是实现类 D 的人可能会想写如下内容:
class D extends class C
{
private int foo; //must be non-static due to multi-threaded new Class D() calls going on
int methodC1() {this.foo = read number from network}
methodC2(int x) {y = this.foo;} //methodC2 is always called after methodC1
//methodA, methodB implementation inherited from C
}
但这不会按预期工作,因为框架实际上会在class D每次调用之前创建一个新对象methodA,methodB因此不能依赖使用“this”引用。
定义methodC1, methodC2asstatic也行不通,因为调用与methodC1in 中的实现相关C,而不是与 in 中的覆盖相关联D。
当真正应该写的是:
class D extends class C
{
int methodC1() {return number from network;}
methodC2(int x) {y = x} //here y is using the return value of methodC1
//methodA, methodB implementation inherited from C
}
我也只 methodC1希望可以被覆盖,methodC2即从事 D 工作的程序员不能乱用methodA
理想的设计应该有
- 属性仅指一类
methodC1,methodC2在那个班级
挑战总结
- 没有,
this_methodC1methodC2 - 做不出
methodC1来methodC2static - 属性只需要一个可实例化的类
我如何设计这个框架?这甚至可以解决吗?您可以更改 , 的methodC1签名methodC2。