简体   繁体   中英

using java generics to extend interfaces or just bad design?

I'm still new to the Java world (former C++ programmer). I designed an Interface hierarchy to force my implementation to @Override the methods in the interfaces. Now I'm in some kind of "how to do this in 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. My problem is both HAVE to implement every method in XMLDecoder AND HTTPDecoder. I believe I have some pretty design but for that :(

Can Java Generics help me solve this problem? 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!


EDIT 1

Sorry for my poor explanation.

The hierarchy is not upside down (on top are the bases).

SSODecoder is my problem. I know it can have either require XMLDecoder OR an HTTPDecoder . Forget about 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.

You should look into an alternative design, where HTTPDecoder and XMLDecoder are strategies that are used by the SSODecoder. Force them to have the same interface, and make SSODecoder delegate to them... whatever responsibility they have.

That way, your call will be something like:

Assertion anAssertion=new Assertion(new XMLDecoder());

我不确定您的“扩展”关系朝哪个方向发展,但是如果Assertion扩展了SSOBindingSSOBinding扩展了SSODecoderSSODecoder扩展了XMLDecoderHTTPDecoder那么如果两个对象分别实现SSOBindingAssertion ,则*两者都将实现XMLDecoderHTTPDecoder每个方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM