Java: Working with multiple complex interfaces without duplicating code

I work with the Java API, which requires me to implement a number of fairly large interfaces. However, usually there is only one or two details that actually differ between implementations, so I made some abstract base classes to provide most of the implementation.

However, now I come across cases when I need to extend some other class and / or implement several such interfaces, and therefore I can not extend my abstract base classes.

In C ++, I was able to use multiple inheritance, as well as use some other tricks, as shown below. However, Java does not allow the use of multiple inheritance or generics in this way.

class MyClass : public HelperForInterfaceA, public HelperForInterfaceB {...};
class template<class BASE> MyHelper : public BASE {...};

The best idea that I have now is to specifically implement my abstract helper class as a field, and then translate all the interface methods into this instance of the field, and the field has a link to the main object to implement the last details, if necessary.

class MyClass extends A implements IB, IC {
    private static class B extends BAbstractHelper {
        private A a;
        public B(A a, int size) {
            super(size);
            this.a = a;
        }

        @Override
        public boolean foo(int x, int y) {
            return a.foo(x, y);
        }
    }
    private static class C extends CAbstractHelper {
        ...
    }


    private B b;
    private C c;
    private int range;

    @Override
    public boolean foo(int x, int y) {
        return x*x + y*y <= range*range;
    }

    @Override
    public float bar(float x, int y, String s) {
        return b.bar(x,y,s);
    }

    ...
}

However, it seems a bit sick, with lots of wrapping methods. Is there a better way to handle this?

+4
source share
1 answer

​​Java . , . . Java IDE . JVM, Scala ( ), .

0

Source: https://habr.com/ru/post/1525349/


All Articles