[英]using java generics to extend interfaces or just bad design?
I'm still new to the Java world (former C++ programmer). 我还是Java世界的新手(前C ++程序员)。 I designed an Interface hierarchy to force my implementation to @Override the methods in the interfaces. 我设计了一个接口层次结构,以强制实现@Override接口中的方法。 Now I'm in some kind of "how to do this in java". 现在,我处于某种“如何在Java中做到这一点”的问题。 All bellow are interfaces. 所有的波纹管都是接口。
XMLDecoder HTTPDecoder
| |
------------------
|
SSODecoder UserStuff
| |
-----------------------------
|
|
SSOBinding
|
|
Assertion
Now the fun part is I have an object implementing SSOBinding and another implementing Assertion. 现在有趣的部分是我有一个实现SSOBinding的对象和另一个实现Assertion的对象。 My problem is both HAVE to implement every method in XMLDecoder AND HTTPDecoder. 我的问题是既要实现的XMLDecoder 和 HTTPDecoder每一个方法。 I believe I have some pretty design but for that :( 我相信我有一些漂亮的设计,但为此:(
Can Java Generics help me solve this problem? Java泛型可以帮助我解决此问题吗? Something like: 就像是:
Assertion<XMLDecoder> anAssertion = new Assertion<XMLDecoder>();
anAssertion.OnlyMethodsInXMLDecoder();
At least that's what I can think of for now but not having any success in implementing this. 至少这是我现在可以想到的,但是在实现这一点上没有任何成功。
Thanks a lot! 非常感谢!
Sorry for my poor explanation. 对不起,我的解释不好。
The hierarchy is not upside down (on top are the bases). 层次结构不是上下颠倒的(最基础是基础)。
SSODecoder is my problem. SSODecoder是我的问题。 I know it can have either require XMLDecoder OR an HTTPDecoder . 我知道它可能需要XMLDecoder或HTTPDecoder 。 Forget about SSOBinding. 忘了SSOBinding。 So I could have an implementation: 所以我可以有一个实现:
class AssertionImpl1 implements Assertion {
// Only implementing XMLDecoder
}
class AssertionImpl2 implements Assertion {
// Only implementing HTTPDecoder
}
The only difference for these to would be the method they need to implement for the decoder. 这些的唯一区别将是它们需要为解码器实现的方法。
Short answer: No. 简短答案:不可以。
I'm guessing that you got your inheritance tree wrong: If not all instances of SSODecoder need to implement the methods in HTTPDecoder and XMLDecoder, then SSODecoder is not a subinterface of both. 我猜测您的继承树错了:如果不是SSODecoder的所有实例都需要在HTTPDecoder和XMLDecoder中实现方法,则SSODecoder不是两者的子接口。
You should look into an alternative design, where HTTPDecoder and XMLDecoder are strategies that are used by the SSODecoder. 您应该研究一种替代设计,其中HTTPDecoder和XMLDecoder是SSODecoder使用的策略。 Force them to have the same interface, and make SSODecoder delegate to them... whatever responsibility they have. 强制它们具有相同的接口,并使SSODecoder委托给它们...无论他们承担什么责任。
That way, your call will be something like: 这样,您的呼叫将类似于:
Assertion anAssertion=new Assertion(new XMLDecoder());
我不确定您的“扩展”关系朝哪个方向发展,但是如果Assertion
扩展了SSOBinding
, SSOBinding
扩展了SSODecoder
和SSODecoder
扩展了XMLDecoder
和HTTPDecoder
那么如果两个对象分别实现SSOBinding
和Assertion
,则*两者都将实现XMLDecoder
和HTTPDecoder
每个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.